A common challenge in testing is not only HOW to test something, but WHAT you can test. That's why I have made a list of all the things I like to test in my applications.
It's a straightforward test, but knowing your home page does not throw an error is crucial. So,
if you want to write your first test, this is the
one to start with.
Reference: Learn more about testing page responses on the official docs.
Testing Page
Response Text
This test is similar to the first page response
test. We also test the response, but this time we
are interested in the content of the response.
It also demos how to test something that is not
shown, which can be helpful too. This test
wouldn't be that helpful if we only have static
text on the home page.
Reference: Learn more about testing page responses on the official docs.
Testing Page
Response View
Next to testing the response status and content,
you can also test the view that is returned.
Reference: Learn more about testing page responses on the official docs.
Testing Against The
Database
Since we store data in the database, we want to
make sure that data is stored correctly. This is
where Laravel can help you with some handy
assertion helpers.
Validation is a crucial part of many applications.
You want to make sure that only valid data can be
submitted. By default, Laravel sends validation
errors back to the user, which we can check with
the assertInvalid method.
Reference: Learn more about validation assertions on the official docs.
Testing Models /
Relationships
First, I like to test every relationship of a
model. To be precise, we do not want to test the
functionality of the relationship; this is what
Laravel already does. We want to make sure that
relationships are defined.
At the end of this controller, we are sending an
email. In our test, we can hit the controller
through an endpoint and make sure this
email would have been sent.
Always run the Mail::fake() method at the
beginning of your tests when testing emails. This
makes sure no actual email is being sent to a
user.
Most helper methods like assertSent also accept
a callback as the second argument. In our case, it
receives the mailable object. It contains all the
email data, like the email to which it needs to be
sent.
This allows you to make even more assertions, like
about the `to-address´ of the email.
Reference: Learn more about testing mailables on the official docs.
Testing Mail
Content
It also makes sense to test the content of an
email. This is especially useful when you have a
lot of emails in your application. You want to
make sure that the content is correct.
PHPPlayer 1 console
1it('contains the product title',function(){
2// Arrange
3$product=Product::factory()->make();
4
5// Act
6$mail=newPaymentSuccessfulMail($product);
7
8// Assert
9 expect($mail)
10->assertHasSubject('Your payment was successful')
This ensures that my job will be pushed to the
queue for a specific trigger, like hitting an
endpoint. Again, the Queue::fake() takes care of
not pushing a job. We do not want to run the job
at this point.
But we still have to test the job, right? Of
course. It contains the crucial logic of this
feature:
In the example above, we test a
notification sent to a user when a new
product is created. We are using the artisan
method to trigger the notification. This is a
great way to test notifications triggered
by a command.
Again, there is a fake method for the notification
facade that makes sure no actual notification is
being sent.
Reference: Learn more about testing notifications on the official docs.
Testing Actions
Actions are just simple classes that have one
specific job. They are a great way to organize
your code, and separate your logic from your
controllers to keep them clean. But how do you
test them?
Let's start again from the outside. First, we want
to test that our action is called when hitting a
specific endpoint.
We can do this by mocking our action class and
expecting that the handle method is called. But,
again, we are here not interested in what our
action does; we want to make sure it is called
when we hit our purchase controller.
To make this work, we must ensure that the
container resolves our action.
Most interesting is the artisan method, which we can call in any Laravel test. It will trigger the command and run it. We can pass the arguments and options to the command as an array. The rest is very similar to other tests.
But there are some more things we can do with commands. We can also expect output of a command like questions or information messages.
PHPPlayer 1 console
1it('asks for user ids',function(){
2// Arrange
3$user=User::factory()->create();
4$userToBeMerged=User::factory()->create();
5
6// Act & Assert
7$this->artisan(MergeAccountsCommand::class)
8->expectsQuestion('Please provide the user ID of the user you want to keep',$user->id)
9->expectsQuestion('Please provide the user ID of the user you want to merge',$userToBeMerged->id)
As you can see in the example above, this is very useful for testing commands that ask for user input. We can also expect output and make sure the command was successful, which means an exit code of 0.
Reference: Learn more about testing commands on the official docs.
Testing Middlewares
A Middleware is always connected to a request, so I like to test the whole request instead of the isolated middleware.
In our example, we have an archive page and first test the page's content.
Similar to custom mocks, we can use the shouldReceive method of the Cache facade to mock the remember method. We can also make sure it is called with the correct parameters and returns the expected result.
Testing File Uploads
Similar to testing mails, notifications, or jobs, we can also test file uploads with the help of a facade.
The fake method of the Storage facade makes sure we do not store any files on our real storage disks. And the UploadedFile class helps us to create test files.
The storage facade also provides handy assertion helpers like assertExists, to make sure the file was uploaded.
Testing
Exceptions
Sometimes it is a good thing when an exception is
thrown because we intentionally want to stop the
execution of our code. We can test that too.
PHPPlayer 1 console
1it('stops if at least one account not found',function(){
We can chain the throws method to our test in
PEST. This will make sure that the exception is
thrown.
Testing Units (Unit
Tests)
Unit tests are great for testing small pieces of
code, like a single method. No other dependencies
are involved. This makes them very fast and easy
to write.
Our example is about a data object. It contains a
method that creates a new instance from an a
webhook payload.
Sometimes you need to make HTTP calls in your
application. This could be to fetch data from an
external API or to send data to another service.
You often want to fake these calls in your tests so you do not have to rely on an external service.
Reference: Learn more about faking HTTP calls on the official docs.
Mocking
Dependencies
When working with code with dependencies, it can
be helpful to mock them. This will let you
concentrate on the logic of your code and not on
the dependencies. This also
means mocking can be useful for any kind of tests.
We already did that when testing
our action classes, but this
works with any dependency. In the following
example, we have a controller with two
dependencies: a payment provider and a mailer.
In our test, we want to focus on testing that the
correct email is being sent. That's why we can
mock the payment provider and expect the handle
method to be called. As a result, our test will
not fail, even though the actual payment provider
is never called.
PEST introduced a new type of test called Architecture Testing. It is a way to test your application's architecture and make sure it is following the rules you defined. This is a great way to make sure your code stays clean and maintainable.
My favorite rule is to check that I didn't forget any debug statements in my code. I am sure you have been there too. You deploy your application to production, and suddenly you see a dd statement on your page. This is embarrassing and can be avoided with architecture tests.
There are many more rules you can define. Read more about them in the official docs.
Conclusion
Being aware of the different types of tests and how to write them is a great skill to have. It will help you write better code and make sure that your application is working as expected.