When talking about automated tests or unit tests in any programming language, there are two groups of people:
- Those who don't write automated tests and think they're a waste of time
- Those who do write tests and then can't imagine their work without them
So, with this article, I will try to convince the former camp to look at the other side and see the benefits, and see how easy it is to start with automated testing in Laravel.
First, let's talk about the "why" and then I'll show a few very basic examples of the "how".
Why You Need Automated Tests
Automated tests are not complicated: they just run parts of your code for you and report any errors. That's the most simple way to describe them. Imagine that you're launching a new feature in your app, and then a personal robot assistant would go and manually test the new functionality for you, also testing if the new code didn't break anything from the old features.
That's the main benefit: re-testing all the features automatically. And it may seem like extra work, but if you don't tell that "robot" to do it, then you should do it manually yourself, right? Or do you just launch the new features without too much testing, hoping that the users would report the bugs? I call that method sarcastically "fingers-crossed-driven development".
With every new feature of your app, automated tests pay off more and more.
- Feature 1: saves X minutes of testing manually
- Feature 2: saves 2X minutes - for feature 2 and feature 1 again
- Feature 3: saves 3X minutes...
- etc.
You get the idea. Imagine your application in a year or two, with new developers on the team who wouldn't even know how that "Feature 1" works or how to reproduce it for testing. So, your future self will thank you massively for writing the automated tests.
Of course, if you think that your project is a very short-term one and you don't care that much about its future... Nah, I believe in your good intentions, so let me show you how it's easy to start testing.
Our First Automated Tests
To run the first automated test in Laravel, you don't need to write any code. Yup, you've read that right. Everything is already configured and prepared in the default Laravel installation, including the first real basic example.
You can try to install a Laravel project and immediately run the first tests:
1laravel new project2cd project3php artisan test
This should be the result in your console:
1 PASS Tests\Unit\ExampleTest2✓ that true is true3 4 PASS Tests\Feature\ExampleTest5✓ the application returns a successful response6 7Tests: 2 passed8Time: 0.10s
If we take a look at the default Laravel /tests
folder, we have two files.
tests/Feature/ExampleTest.php:
1class ExampleTest extends TestCase2{3 public function test_the_application_returns_a_successful_response()4 {5 $response = $this->get('/');6 7 $response->assertStatus(200);8 }9}
There's no need to know any syntax, to understand what is happening here: loading the homepage and checking if the HTTP status code is "200 OK".
Also notice how the method name test_the_application_returns_a_successful_response()
becomes readable text when viewing the test results, just replacing the underscore symbol with a space.
tests/Unit/ExampleTest.php:
1class ExampleTest extends TestCase2{3 public function test_that_true_is_true()4 {5 $this->assertTrue(true);6 }7}
This looks a bit pointless, checking that true is true? We'll talk about unit tests specifically, a bit later. For now, you need to understand what is generally happening in every test.
- Each test file in the
tests/
folder is a PHP Class extending the TestCase of PHPUnit - Inside of each class, you may create multiple methods, usually one method for one situation to be tested
- Inside of each method, there are three actions: preparation of the situation, then action, and then checking (asserting) if the result is as expected
Structurally, that's all you need to know, everything else depends on the exact things you want to test.
To generate an empty test class, you just run this command:
1php artisan make:test HomepageTest
It would generate the file tests/Feature/HomepageTest.php
:
1class HomepageTest extends TestCase 2{ 3 // Replace this method with your own ones 4 public function test_example() 5 { 6 $response = $this->get('/'); 7 8 $response->assertStatus(200); 9 }10}
What If Tests Fail?
Let me show you what happens if the test assertions don't return the expected result.
Let's edit the example tests to this:
1class ExampleTest extends TestCase 2{ 3 public function test_the_application_returns_a_successful_response() 4 { 5 $response = $this->get('/non-existing-url'); 6 7 $response->assertStatus(200); 8 } 9}10 11 12class ExampleTest extends TestCase13{14 public function test_that_true_is_false()15 {16 $this->assertTrue(false);17 }18}
And now, if we run php artisan test
again:
1 2 FAIL Tests\Unit\ExampleTest 3⨯ that true is true 4 5 FAIL Tests\Feature\ExampleTest 6⨯ the application returns a successful response 7 8--- 9 10• Tests\Unit\ExampleTest > that true is true11Failed asserting that false is true.12 13at tests/Unit/ExampleTest.php:1614 12▕ * @return void15 13▕ */16 14▕ public function test_that_true_is_true()17 15▕ {18➜ 16▕ $this->assertTrue(false);19 17▕ }20 18▕ }21 19▕22 23• Tests\Feature\ExampleTest > the application returns a successful response24Expected response status code [200] but received 404.25Failed asserting that 200 is identical to 404.26 27at tests/Feature/ExampleTest.php:1928 15▕ public function test_the_application_returns_a_successful_response()29 16▕ {30 17▕ $response = $this->get('/non-existing-url');31 18▕32➜ 19▕ $response->assertStatus(200);33 20▕ }34 21▕ }35 22▕36 37 38Tests: 2 failed39Time: 0.11s
As you can see, there are two statements marked as FAIL, with explanations below and arrows to the exact test line that failed the assertion. So this is how the errors are shown. Convenient, isn't it?
Simple Real-Life Example: Registration Form
Let's get more practical and look at a real-life example. Imagine that you have a form, and you need to test various cases: check if it fails if filled with invalid data, check if it succeeds with the correct input, etc.
Did you know that the official Laravel Breeze starter kit comes with the feature tests inside? So, let's take a look at a few examples from there:
tests/Feature/RegistrationTest.php
1use App\Providers\RouteServiceProvider; 2use Illuminate\Foundation\Testing\RefreshDatabase; 3use Tests\TestCase; 4 5class RegistrationTest extends TestCase 6{ 7 use RefreshDatabase; 8 9 public function test_registration_screen_can_be_rendered()10 {11 $response = $this->get('/register');12 13 $response->assertStatus(200);14 }15 16 public function test_new_users_can_register()17 {18 $response = $this->post('/register', [19 'name' => 'Test User',20 'email' => 'test@example.com',21 'password' => 'password',22 'password_confirmation' => 'password',23 ]);24 25 $this->assertAuthenticated();26 $response->assertRedirect(RouteServiceProvider::HOME);27 }28}
Here we have two tests in one class, as they are both related to the registration form: one is checking if the form is loaded correctly, and another one checks if the submission works well.
No comments:
Post a Comment