Laravel natively supports testing code using frameworks dedicated to writing tests. We have a choice between two frameworks: PHPUnit and PEST. PHPUnit is installed by default. Laravel itself also provides a set of functions to check the code we write. We can test various aspects related to responses, from headers trough status codes to responses. We can also create mock instances of various services like email servers or storage disks on the server for testing purposes.
Additionally, we receive a set of Artisan commands dedicated to testing. Besides running tests, we can also enforce code coverage checks, specifying the minimum coverage that the application must meet for the tests to pass. We can verify which tests run slowest or run them in parallel. The rest of the options can be viewed using the –help option when invoking the command.
php artisan test --help
PHPUnit
PHPUnit is the default testing framework installed with Laravel. It offers functionalities such as a set of asserts, the ability to prepare the application before each test, and support for data providers. Code in PHPUnit is written in classes and methods. Each file represents one class in which we can write multiple methods, and within these methods, we write the logic of tests and asserts for our code. This way of writing tests is similar to writing code for a normal application, so it may be more natural for the programmer. PEST, on the other hand, allows us to do things differently.
//PHPUnit public function test_sum(): void { $result = sum(1,2); $this->assertEquals(3, $result); }
PEST
PEST is an alternative framework that can be installed along with Laravel. As stated on the official website, PEST is built on top of PHPUnit but extends it with additional features. Tests in PEST are written differently. Instead of using the class and method structure, we use an empty PHP file where we call the test functions, pass the test name, and create an anonymous function with the test logic. Additionally, instead of using asserts, which are also present in PEST, it is proposed to use expectations that can be method chained.
//PEST test('sum', function () { $result = sum(1, 2); expect($result)->toBe(3); });