Testing in Laravel 9 For Beginners: PHPUnit, Pest, TDD

Default Tests: How They Work and How to Launch Them

Let's start this course by looking at the default tests when a new Laravel project is created. You can see a folder named tests with Feature and Unit tests.

tests directory

We will talk more deeply about their differences later in the course. But mainly, most of your tests should be feature. This means you test some feature to see whether it works or not. Unit tests are more about separate, so-called units of your code like a function. You would test that a function internally works correctly. We will focus most on the feature tests in this course.

Now let's look at what is the ExampleTest in the tests/Feature folder.

ExampleTest is a class that extends the TestCase, and every test or feature to be tested is a function. The test class may contain multiple functions. In each function, you execute some code and then test or assert that something happened and whether it's correct. For example, in this example test case:

public function test_the_application_returns_a_successful_response(): void
$response = $this->get('/');

We get the home page URL and assert that the status of that request is 200.

To run these tests in the terminal, we need to run a command that will execute all Feature and Unit tests.

php artisan test

run tests command

We can see that two tests passed. One from Unit and one from Feature tests. The names for the tests come from the naming of the function. When naming the test function, don't be afraid of longer names because those will be readable when someone launches tests in the feature.

Now, what happens when a test fails? Let's change the status and re-run the tests.

public function test_the_application_returns_a_successful_response(): void
$response = $this->get('/');

failed test

Now we can see that 1 passed and 1 failed. And inside, we can see which test failed and on which line. And it shows the actual error Expected response status code [403] but received 200.. This is what a failed test would look like.

So you can see how easy it is to start testing. Most of the tests are just launching some page or calling some API and then testing whether it is successful. There is a specific kind of test called smoked tests, which goes through all the pages and tests if the page returns 200 or whatever the status code expected.

Even these tests would be a great start to ensure your application works when you launch a new feature. All the other parts of the automated testing are about exploring different assertions and ways to simulate those scenarios for specific pages or functionality.

No comments or questions yet...