WARNING You're browsing the documentation for an upcoming version of Laravel. The documentation and features of this release are subject to change.
Laravel is built with testing in mind. In fact, support for testing withPest andPHPUnit is included out of the box and aphpunit.xml file is already set up for your application. The framework also ships with convenient helper methods that allow you to expressively test your applications.
By default, your application'stests directory contains two directories:Feature andUnit. Unit tests are tests that focus on a very small, isolated portion of your code. In fact, most unit tests probably focus on a single method. Tests within your "Unit" test directory do not boot your Laravel application and therefore are unable to access your application's database or other framework services.
Feature tests may test a larger portion of your code, including how several objects interact with each other or even a full HTTP request to a JSON endpoint.Generally, most of your tests should be feature tests. These types of tests provide the most confidence that your system as a whole is functioning as intended.
AnExampleTest.php file is provided in both theFeature andUnit test directories. After installing a new Laravel application, execute thevendor/bin/pest,vendor/bin/phpunit, orphp artisan test commands to run your tests.
When running tests, Laravel will automatically set theconfiguration environment totesting because of the environment variables defined in thephpunit.xml file. Laravel also automatically configures the session and cache to thearray driver so that no session or cache data will be persisted while testing.
You are free to define other testing environment configuration values as necessary. Thetesting environment variables may be configured in your application'sphpunit.xml file, but make sure to clear your configuration cache using theconfig:clear Artisan command before running your tests!
.env.testing Environment FileIn addition, you may create a.env.testing file in the root of your project. This file will be used instead of the.env file when running Pest and PHPUnit tests or executing Artisan commands with the--env=testing option.
To create a new test case, use themake:test Artisan command. By default, tests will be placed in thetests/Feature directory:
1phpartisanmake:testUserTestIf you would like to create a test within thetests/Unit directory, you may use the--unit option when executing themake:test command:
1phpartisanmake:testUserTest--unitTest stubs may be customized usingstub publishing.
Once the test has been generated, you may define test as you normally would using Pest or PHPUnit. To run your tests, execute thevendor/bin/pest,vendor/bin/phpunit, orphp artisan test command from your terminal:
1<?php2 3test('basic',function(){4 expect(true)->toBeTrue();5}); 1<?php 2 3namespace Tests\Unit; 4 5use PHPUnit\Framework\TestCase; 6 7classExampleTestextendsTestCase 8{ 9/**10 * A basic test example.11*/12publicfunctiontest_basic_test():void13 {14$this->assertTrue(true);15 }16}If you define your ownsetUp /tearDown methods within a test class, be sure to call the respectiveparent::setUp() /parent::tearDown() methods on the parent class. Typically, you should invokeparent::setUp() at the start of your ownsetUp method, andparent::tearDown() at the end of yourtearDown method.
As mentioned previously, once you've written tests, you may run them usingpest orphpunit:
1./vendor/bin/pest1./vendor/bin/phpunitIn addition to thepest orphpunit commands, you may use thetest Artisan command to run your tests. The Artisan test runner provides verbose test reports in order to ease development and debugging:
1phpartisantestAny arguments that can be passed to thepest orphpunit commands may also be passed to the Artisantest command:
1phpartisantest--testsuite=Feature--stop-on-failureBy default, Laravel and Pest / PHPUnit execute your tests sequentially within a single process. However, you may greatly reduce the amount of time it takes to run your tests by running tests simultaneously across multiple processes. To get started, you should install thebrianium/paratest Composer package as a "dev" dependency. Then, include the--parallel option when executing thetest Artisan command:
1composerrequirebrianium/paratest--dev2 3phpartisantest--parallelBy default, Laravel will create as many processes as there are available CPU cores on your machine. However, you may adjust the number of processes using the--processes option:
1phpartisantest--parallel--processes=4When running tests in parallel, some Pest / PHPUnit options (such as--do-not-cache-result) may not be available.
As long as you have configured a primary database connection, Laravel automatically handles creating and migrating a test database for each parallel process that is running your tests. The test databases will be suffixed with a process token which is unique per process. For example, if you have two parallel test processes, Laravel will create and useyour_db_test_1 andyour_db_test_2 test databases.
By default, test databases persist between calls to thetest Artisan command so that they can be used again by subsequenttest invocations. However, you may re-create them using the--recreate-databases option:
1phpartisantest--parallel--recreate-databasesOccasionally, you may need to prepare certain resources used by your application's tests so they may be safely used by multiple test processes.
Using theParallelTesting facade, you may specify code to be executed on thesetUp andtearDown of a process or test case. The given closures receive the$token and$testCase variables that contain the process token and the current test case, respectively:
1<?php 2 3namespace App\Providers; 4 5use Illuminate\Support\Facades\Artisan; 6use Illuminate\Support\Facades\ParallelTesting; 7use Illuminate\Support\ServiceProvider; 8use PHPUnit\Framework\TestCase; 9 10classAppServiceProviderextendsServiceProvider11{12/**13 * Bootstrap any application services.14*/15publicfunctionboot():void16 {17ParallelTesting::setUpProcess(function(int$token) {18// ...19 });20 21ParallelTesting::setUpTestCase(function(int$token,TestCase$testCase) {22// ...23 });24 25// Executed when a test database is created...26ParallelTesting::setUpTestDatabase(function(string$database,int$token) {27Artisan::call('db:seed');28 });29 30ParallelTesting::tearDownTestCase(function(int$token,TestCase$testCase) {31// ...32 });33 34ParallelTesting::tearDownProcess(function(int$token) {35// ...36 });37 }38}If you would like to access the current parallel process "token" from any other location in your application's test code, you may use thetoken method. This token is a unique, string identifier for an individual test process and may be used to segment resources across parallel test processes. For example, Laravel automatically appends this token to the end of the test databases created by each parallel testing process:
1$token=ParallelTesting::token();When running your application tests, you may want to determine whether your test cases are actually covering the application code and how much application code is used when running your tests. To accomplish this, you may provide the--coverage option when invoking thetest command:
1phpartisantest--coverageYou may use the--min option to define a minimum test coverage threshold for your application. The test suite will fail if this threshold is not met:
1phpartisantest--coverage--min=80.3The Artisan test runner also includes a convenient mechanism for listing your application's slowest tests. Invoke thetest command with the--profile option to be presented with a list of your ten slowest tests, allowing you to easily investigate which tests can be improved to speed up your test suite:
1phpartisantest--profileWhen running tests, Laravel boots the application for each individual test method. Without a cached configuration file, each configuration file in your application must be loaded at the start of a test. To build the configuration once and re-use it for all tests in a single run, you may use theIlluminate\Foundation\Testing\WithCachedConfig trait:
1<?php2 3use Illuminate\Foundation\Testing\WithCachedConfig;4 5pest()->use(WithCachedConfig::class);6 7// ... 1<?php 2 3namespace Tests\Feature; 4 5use Illuminate\Foundation\Testing\WithCachedConfig; 6use Tests\TestCase; 7 8classConfigTestextendsTestCase 9{10useWithCachedConfig;11 12// ...13} Laravel is the most productive way to
build, deploy, and monitor software.