Quick start: integrate PHPUnit to write test cases


brief introduction

Larravel is rooted in testing. In fact, the built-in PHPUnit supports testing out of the box, and phpunit.xml The file has been set up for the application. The framework also provides convenient auxiliary methods to allow you to test applications gracefully.

By default, tests The directory contains two subdirectories: Feature and Unit , which are used for functional testing and unit testing respectively. Unit testing focuses on small, isolated code. In fact, most unit tests may focus on a single method. Functional testing can be used to test code in large blocks, including previous interactions of several components, or even a complete HTTP request.

Feature and Unit The test directory provides ExampleTest.php File. After installing the new Larravel application, simply run it in the project root directory phpunit You can run the test (if you are prompted that you cannot find the command, you can use the cp vendor/bin/phpunit ./ Copy the command):

Note: PHPUnit is a powerful PHP unit testing framework for programmers. If you have not touched PHPUnit before, you can use Official website and Chinese documents Quick Start.

Environmental Science

When running the test, Larravel will automatically set the environment to testing , this is because phpunit.xml Environment variables are defined in. Larave also automatically configures the session and cache driver as array , which means that the storage session and cache will not be persisted during the test.

If necessary, you can also define other test environment configuration values. testing Environment variables can be set in phpunit.xml File, but make sure to use Artisan commands before running commands config:clear Clear the configuration cache.

In addition, you can also create a .env.testing File, which will run the PHPUnit test or execute the --env=testing Override the Artisan command of the switch .env Environment variables in the file.

Create&Run Test

To create a new test case, you can use the Artisan command make:test

 //Create a test class in the Feature directory php artisan make:test UserTest //Create a test class in the Unit directory php artisan make:test UserTest --unit

After creating the test class, you can define the test method just like using PHPUnit. To run the test, just execute it on the terminal phpunit Command:

 <? php namespace Tests\Unit; use Tests\TestCase; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class ExampleTest extends TestCase { /** *Simple test example * * @return void */ public function testBasicTest() { $this->assertTrue(true); } }
Note: If you define your own setUp Method, ensure that the parent::setUp()

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: Implementation of Timed Task Scheduling in Laravel

>>Next: HTTP test: how to test HTTP requests and responses