0
0
Laravelframework~30 mins

PHPUnit setup in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
PHPUnit Setup in Laravel
📖 Scenario: You are building a Laravel web application and want to ensure your code works correctly by writing automated tests. Laravel uses PHPUnit as its testing framework.Setting up PHPUnit properly in your Laravel project is the first step to start writing tests.
🎯 Goal: Set up PHPUnit testing in a Laravel project by configuring the test database connection, creating a test case, and running a basic test.
📋 What You'll Learn
Create a phpunit.xml configuration file with the correct environment settings
Set up a test database connection in .env.testing
Create a basic test class extending TestsTestCase
Write a simple test method that asserts true is true
Run PHPUnit tests using the php artisan test command
💡 Why This Matters
🌍 Real World
Automated testing helps catch bugs early and ensures your Laravel application works as expected before deployment.
💼 Career
Knowing how to set up and run PHPUnit tests is essential for Laravel developers to maintain code quality and collaborate in teams.
Progress0 / 4 steps
1
Create phpunit.xml Configuration File
Create a phpunit.xml file in the root of your Laravel project with the following content exactly: set the APP_ENV to testing, and configure the DB_CONNECTION to sqlite with an in-memory database by setting DB_DATABASE=:memory: inside the phpunit.xml environment variables.
Laravel
Need a hint?

The phpunit.xml file sets environment variables for testing. Use APP_ENV as testing and configure the database to use SQLite in-memory.

2
Create .env.testing File for Test Environment
Create a file named .env.testing in the root of your Laravel project. Inside it, set DB_CONNECTION=sqlite and DB_DATABASE=:memory: exactly as shown.
Laravel
Need a hint?

The .env.testing file overrides environment variables when running tests. It should match the database settings in phpunit.xml.

3
Create a Basic Test Class
Create a new PHP test class file named ExampleTest.php inside the tests/Feature directory. Define a class ExampleTest that extends Tests\TestCase. Inside it, write a public method test_true_is_true that asserts true is true using $this->assertTrue(true);.
Laravel
Need a hint?

Test classes extend Tests\TestCase. Test methods start with test and use assertions like assertTrue.

4
Run PHPUnit Tests Using Artisan
Run the Laravel test suite using the command php artisan test in your terminal to execute the tests you created.
Laravel
Need a hint?

Use php artisan test to run all tests in your Laravel project.