Laravel How to Run Tests: Commands, Speed, and Safety
Run your Laravel test suite, target individual files, and configure parallel execution safely. This guide is for Laravel engineers managing automated testing pipelines.
On this page
To run tests in Laravel, execute php artisan test from the root directory of your project. This command boots your application environment, runs your test suite, and outputs formatted results to your terminal.
Modern Laravel applications build on either traditional PHPUnit classes or Pest PHP. Pest, created by Nuno Maduro, runs on the PHPUnit engine under the hood and offers an expressive, functional syntax inspired by Jest. Laravel 11, released in 2024 and supported through 2026, defaults to Pest during initial application scaffolding while retaining full support for PHPUnit. Both frameworks use the same Artisan runner. Regardless of which syntax style your team chooses, you execute and manage them using the exact same command-line workflow.
Step-by-step test execution#
Running tests across your application requires setting up your terminal and verifying your target configuration before execution.
- Open your terminal and navigate to your Laravel project root directory.
- Verify that your
.env.testingfile orphpunit.xmlconfiguration defines safe database credentials so you do not overwrite local data. - Run
php artisan testto execute your entire test suite. - Pass relative paths or arguments to target specific test classes, directories, or individual test methods.
- Review the test summary in your terminal for failures, warnings, and execution times.
Laravel organizes tests into two standard directories: tests/Unit and tests/Feature. Unit tests evaluate isolated PHP classes, helpers, and pure business logic without booting database connections or HTTP kernels. Feature tests boot the full application container, test database interactions, evaluate middleware, and verify JSON responses. Laravel 11 streamlined the default project skeleton by generating fewer boilerplate files, but these two test directories remain the standard locations for all test files.
Targeting specific test files and filters#
Running your entire test suite every time you make a change creates unnecessary delay. You can direct the Artisan test runner to execute a single file by passing its relative path.
php artisan test tests/Feature/AuthenticationTest.php
You can target an entire subfolder using the directory path:
php artisan test tests/Feature
When you need to debug a single failing test inside a large file, use the --filter flag. The filter argument accepts the method name of a PHPUnit test or the description string of a Pest test.
php artisan test --filter=test_user_can_login
You can also use partial matching in the filter argument to execute a subset of related tests:
php artisan test --filter=test_users_can_be_created
Filtering cuts your feedback loop from minutes to seconds during local debugging sessions. Once your targeted test passes, run the parent directory or full suite to ensure no regressions occurred elsewhere.
Preventing database destruction and isolating state#
The primary operational risk when running tests is database destruction. When running tests, Laravel automatically sets the application environment to testing. It looks for configuration values inside .env.testing first. If that file does not exist, it loads environment variables defined in your phpunit.xml (or pest.xml) file. If neither file defines distinct database values, Laravel falls back to your standard .env file, putting your local development data at risk.
To prevent test runs from affecting your local development database, set up an in-memory SQLite database inside your phpunit.xml file or .env.testing.
<php>
<env name="APP_ENV" value="testing"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
</php>
When using :memory:, SQLite creates a temporary database entirely in RAM. It builds the schema on invocation and discards it as soon as the test process terminates. This keeps execution fast and eliminates disk cleanup tasks.
To keep database records isolated between individual test cases, attach the RefreshDatabase trait to your test classes or Pest test files.
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class AuthenticationTest extends TestCase
{
use RefreshDatabase;
public function test_user_can_login(): void
{
$response = $this->get('/login');
$response->assertStatus(200);
}
}
The RefreshDatabase trait wraps each test inside an active database transaction and rolls it back once the test finishes. If the database does not support transactions, or if you run migrations for the first time during the suite, it resets the database schema before executing the assertions.
Speeding up test suites with parallel execution#
As test suites expand past several hundred tests, serial execution becomes a bottleneck. Laravel provides native parallel execution using the --parallel flag.
php artisan test --parallel
Under the hood, Laravel leverages the brianium/paratest package to distribute test files across multiple CPU cores. Running tests concurrently shortens execution times significantly, especially for suites heavy with database interactions.
Parallel execution introduces concurrency concerns when multiple processes hit the same database tables at the same time. Laravel resolves this by spinning up dedicated test databases for each parallel process. For this mechanism to function, your config/database.php file must allow dynamic database creation. Laravel creates temporary databases labeled with process tokens, executes migrations against each one, runs the distributed tests, and drops the temporary databases when the run finishes.
If your system lacks necessary database creation privileges or if process tokens are misconfigured in your environment, parallel runs will collide and produce false assertion errors. Verify your database user permissions before relying on parallel execution in local or automated staging environments.
Testing HTTP endpoints and mocking application facades#
Feature tests frequently verify HTTP endpoints without booting external web servers. Laravel includes built-in HTTP helpers that route simulated requests through the HTTP kernel.
public function test_user_creation_endpoint(): void
{
$response = $this->postJson('/api/users', [
'name' => 'Muhammad Zubair',
'email' => '[email protected]',
]);
$response->assertStatus(201)
->assertJson(['created' => true]);
}
Helpers like $this->get(), $this->post(), and $this->postJson() invoke your controllers, route bindings, and middleware directly in memory.
When testing endpoints that trigger external actions—like processing background jobs, sending emails, or firing domain events—use Laravel facade mocks. Laravel allows you to fake these systems so they do not execute side effects during test runs.
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Queue;
public function test_order_dispatch_workflow(): void
{
Queue::fake();
Event::fake();
Notification::fake();
$response = $this->postJson('/api/orders', ['item_id' => 12]);
$response->assertStatus(200);
Queue::assertPushed(ProcessOrderJob::class);
}
Mocking facades like Queue::fake(), Event::fake(), and Notification::fake() prevents downstream operations from executing, allowing your tests to verify that jobs were dispatched without sending network calls or writing to queue tables.
Running tests in CI and generating coverage#
Continuous Integration (CI) systems require fast feedback and explicit failure reporting. When running tests inside CI workflows, use the --stop-on-failure flag.
php artisan test --stop-on-failure
This flag halts execution immediately when any single assertion fails. In large pipelines, stopping on the first failure avoids wasting compute minutes on a run that has already failed.
If your build pipeline tracks test metrics, generate a code coverage report by appending the --coverage flag:
php artisan test --coverage
Generating code coverage requires an active driver installed in your PHP environment, such as PCOV or Xdebug. Running coverage with PCOV is substantially faster than with Xdebug because PCOV is designed specifically for code coverage analysis rather than step debugging.
Comparing execution options#
Choose your testing approach based on your application architecture, test suite volume, and team preferences.
| Approach / Tool | Primary Use Case | Execution Speed | Syntax Style |
|---|---|---|---|
php artisan test (PHPUnit) |
Traditional OOP-style assertions ($this->assertEquals()) |
Fast | Class/Method based |
php artisan test (Pest) |
Modern expressive testing (test('it works', function () { ... })) |
Fast (runs on PHPUnit engine) | Functional / Fluent |
php artisan test --parallel |
Large production test suites with heavy database operations | Significantly faster (multi-process) | Same as above |
Exact future deprecation timelines for legacy PHPUnit assertion syntax within Pest are unconfirmed, though backward compatibility remains robust as of late 2026. Both Pest and PHPUnit test files can run side-by-side in the same project under the same Artisan command.
Frequently asked questions#
How do I run a single test in Laravel?#
Pass the relative path of the test file directly to the Artisan test command. For example, run php artisan test tests/Feature/UserTest.php. If you only want to run one specific method inside that file, append the filter flag: php artisan test tests/Feature/UserTest.php --filter=test_user_can_register.
How do I run tests without wiping my local database?#
Define a dedicated testing database connection in your .env.testing file or the <php> block of your phpunit.xml configuration file. The standard approach is setting DB_CONNECTION=sqlite and DB_DATABASE=:memory:, which isolates all testing operations to RAM and prevents changes to your development database.
What is the difference between php artisan test and vendor/bin/phpunit?#
php artisan test is Laravel's custom wrapper around PHPUnit and Pest. It provides cleaner terminal output, native collision reporting, support for the --parallel flag, and automatic environment detection. Invoking vendor/bin/phpunit executes the underlying PHPUnit binary directly without Laravel's custom CLI formatting.
How do I run tests in parallel in Laravel?#
Add the --parallel flag to your command: php artisan test --parallel. Laravel coordinates with the brianium/paratest package to distribute tests across multiple worker processes and manages isolated temporary databases for each process automatically.
How do I filter tests by name?#
Use the --filter option followed by the test method name or description string: php artisan test --filter=test_users_can_be_created. The filter argument performs substring matching across test methods and Pest test blocks.
How do I set environment variables specifically for testing?#
Define your testing variables inside the .env.testing file at the root of your application, or declare them inside the <php> block of your phpunit.xml file. Variables declared in these locations take precedence over values in your standard .env file during test execution.
How do I stop test execution on the first failure?#
Execute php artisan test --stop-on-failure. When Laravel encounters an assertion that fails or an unhandled exception, it terminates the test run immediately, preventing subsequent tests from executing.
To get started, open your project terminal and run php artisan test. Then inspect your phpunit.xml file to ensure your database connection is safely configured before writing feature tests.