Test are an important part of programming. Tests ensure that the code you wrote actually works. There are two ways to work with test, one way is to write the code and write the tests for the code or the other way is called Test-Driven Development or TDD for short.
In TDD you write the test first and after the code. Meaning that you think what your application needs to be able to do or what it should be capable of doing and write the test for that. After which you write the code to make those tests pass. So during the coding process your goal basically is to make the test error message change, because that means that your changing something that affects the test and are therefor in the right place.
AAA
When working with unit tests you usually go with AAA (Assert, Act & Assert) structuring / pattern. Sticking to these three clearly labelled steps makes tests easier to read, keeps setup separate from verification, and helps spot what’s really being exercised in each test.
Assert
Assert is where you set up everything the test needs: create objects, mock dependencies, put data in the right state. Here are 2 examples:
// Example 1:
$employer = Employer::factory()->create();
$job = Job::factory()->create([
'employer_id' => $employer->id,
]);
// Example 2:
$job = Job::factory()->create();Put the system in the exact state the test needs. Create models, seed relationships, stub time, etc.
Act
Act is the part where you run the specific function or method you want to test. Here are 2 examples:
// Example 1:
expect($job->employer->is($employer))->toBeTrue();
// Example 2:
$job->tag('Frontend');Execute one behaviour you’re verifying. Keep it to a single statement so the reader’s eye is drawn to it.
Assert
Assert is where you check that the result or side-effects match the expected outcome. Here are 2 examples:
// Example 1:
expect($job->employer->is($employer))->toBeTrue();
// Example 2:
expect($job->tags)->toHaveCount(1);Prove the behaviour did what you expect. Check the return value or side-effects.
Now one thing you might have noticed is that in the “Example 1” that in “Act” and “Assert” the code is the same, that is because sometimes they aren’t separate. Meaning that that line of code is responsible for both the “Act” and “Assert” part of the test. That is because in the first test the act is implicit—accessing $job->employer triggers Laravel’s relationship lookup.
