0
0
LaravelHow-ToBeginner · 4 min read

How to Use PHPUnit in Laravel: Simple Testing Guide

To use phpunit in Laravel, run php artisan test or vendor/bin/phpunit in your project root. Laravel integrates PHPUnit by default and uses the tests/ directory for test files written as PHP classes extending TestCase.
📐

Syntax

Laravel uses PHPUnit for testing. You run tests with php artisan test or directly with vendor/bin/phpunit. Test classes extend Tests\TestCase and contain methods starting with test or annotated with @test.

Each test method contains assertions like $this->assertTrue() to check expected outcomes.

php
<?php
namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_basic_test()
    {
        $response = $this->get('/');
        $response->assertStatus(200);
    }
}
💻

Example

This example shows a simple feature test that checks if the home page returns a 200 status code.

php
<?php
namespace Tests\Feature;

use Tests\TestCase;

class HomePageTest extends TestCase
{
    public function test_home_page_returns_success()
    {
        $response = $this->get('/');
        $response->assertStatus(200);
    }
}
Output
OK (1 test, 1 assertion)
⚠️

Common Pitfalls

  • Not running composer install to get PHPUnit before testing.
  • Writing test methods without the test prefix or @test annotation, so PHPUnit ignores them.
  • Not extending Tests\TestCase, which provides Laravel testing helpers.
  • Forgetting to set up environment variables for testing, causing database connection errors.
php
<?php
// Wrong: Missing 'test' prefix and not extending TestCase
class WrongTest
{
    public function checkHomePage()
    {
        // This will not run
    }
}

// Right: Proper test method and class
namespace Tests\Feature;
use Tests\TestCase;

class CorrectTest extends TestCase
{
    public function test_check_home_page()
    {
        $this->get('/')->assertStatus(200);
    }
}
📊

Quick Reference

Here is a quick summary of commands and file locations for PHPUnit in Laravel:

Command / LocationDescription
php artisan testRun all tests with Laravel's wrapper
vendor/bin/phpunitRun PHPUnit directly
tests/FeatureFolder for feature tests (HTTP, UI)
tests/UnitFolder for unit tests (logic, classes)
Tests\TestCase.phpBase test class with Laravel helpers

Key Takeaways

Run tests in Laravel using 'php artisan test' or 'vendor/bin/phpunit'.
Write test classes extending 'Tests\TestCase' with methods starting with 'test'.
Place feature tests in 'tests/Feature' and unit tests in 'tests/Unit'.
Ensure PHPUnit is installed via Composer before running tests.
Use assertions like '$this->assertStatus()' to verify expected results.