Unit Testing on Laravel
Unit testing is a software testing technique in which "units"—individual programme components—are tested. Developers write unit tests to ensure that their code works appropriately—this aids in the detection and prevention of bugs in the future. A typical unit test cycle is as follows:
Pull code from the repository, Set Test acceptance criteria, Execute the unit tests, make changes if required, Code review, and push and merge code into the repository.
This will be a series of blog posts where we will publish helper documents for mastering unit testing on a Laravel app.
The test-driven development (TDD) has gained much attention for efficient software delivery. This creates specific test cases that the software must pass to be 'shippable'.
Laravel supports two types of tests, Feature tests and Unit Tests. Laravel is built on robust testing philosophy. Laravel supports unit testing through an out of the box feature called phpunit.xml. Tests are run in a different environment. All the test variables are configured with the phpunit.xml file. By default, Laravel runs all the tests on the testing environment, variables derived from phpunit.xml.
Configuration
Laravel allows unit tests for units involving databases. However, to ensure that the actual database remains unaffected by the tests, Laravel allows an in-memory version using SQLite. To specify a distinct database relation for the testing environment, add the following line of code to phpunit.xml
And then configure the connection inside config/database.php
'sqlite_filename' =>
'driver' => 'sqlite',
'database' => ':memory:'
The illustration above will define a new sqlite_filename connection using SQLite. We are creating this database in memory by using the unique database property value :memory: .
Run-> php artisan config:clear before you run the tests.
A unit test can be divided into three parts - Arrange, Act and Assert.
Arrange - sets up the object for the test.
Act - tests the object set up during the ARRANGE phase.
Assert - Checks and verifies the result from the ACT phase against the criteria for acceptance.
Creating a test
In Laravel, you can use the artisan command make:test to create a test case. By default, such test cases will be found under test/Feature. To create a unit test case, use the command
php artisan make:test TestCase --unit
Important point: Please note that all the unit test methods should start with the name Test
Run the test
To run the test, you can either use:
./vendor/bin/phpunit command
or
php artisan test