Underlying Test Case

Overview

The closure you provide to your test function is always bound to a specific test case class. By default, that class is PHPUnit\Framework\TestCase:

1<?php
2
3it('has home', function () {
4 $this->assertTrue(true);
5
6 // \PHPUnit\Framework\TestCase
7 echo get_class($this);
8});

In real-world applications, you may have to change it, and for that, you can call the uses function:

uses()

The uses function binds a class, trait and/or closure to your test files. This is how you would bind a trait to your current file:

1<?php
2
3use Illuminate\Foundation\Testing\RefreshDatabase;
4
5// Uses the given trait in the current file
6uses(RefreshDatabase::class);

The in() function lets you use the given class, trait, or closure recursively inside the specified folder:

1<?php
2
3use Tests\TestCase;
4
5// Uses the given test case in the "Feature" folder recursively
6uses(TestCase::class)->in('Feature');

You can use multiple uses() calls if they target different folders:

1<?php
2
3use Tests\TestCase;
4use Illuminate\Foundation\Testing\RefreshDatabase;
5
6// Uses the given test case in the "Feature" folder recursively
7uses(TestCase::class)->in('Feature');
8
9// Uses the given trait in the "Unit" folder recursively
10uses(RefreshDatabase::class)->in('Unit');
11
12// Uses the given `beforeEach` setup closure in the "Regression" folder recursively
13// the same can be done for `beforeall`, `afterEach` and `afterAll`
14uses()->beforeEach(fn () => dump('foo'))->in('Regression');

To bind multiple classes and/or traits at once, group them in your uses() call like so:

1<?php
2
3use Tests\TestCase;
4use Illuminate\Foundation\Testing\RefreshDatabase;
5
6// Uses the given test case and trait in the current folder recursively
7uses(TestCase::class, RefreshDatabase::class)->in(__DIR__);

In some cases it is not enough to just add the trait with uses(), for these situations you can also call a function on the trait like so:

1uses(CreatesApplication::class);
2
3beforeEach()->createApplication();

tests/Pest.php

Please consider creating a file with the name tests/Pest.php on the root directory of your tests folder. No worries, that file is autoloaded automatically. It's an ideal place to recursively bind traits and classes to your tests with the uses() function.

1tests
2 - Unit/ComponentTest.php
3 - Feature/HomeTest.php
4 - Pest.php <--
5phpunit.xml

Next section: Assertions →