Unit Test Getters and Setters in Laravel

In this post, we’re going to look at a simple way of unit testing a Model’s getters and setters.

We won’t go into the debate on whether or not it’s ok to write specific tests for getters and setters.

I think that’s a topic for another post.

Anyway, let’s find out how we can unit test getters and setters of a Model.


The Model

In this example, we’re going to unit test the User Model.

This Model has several attributes such as firstName, lastName, phone and email.

Each attribute has its own set of getters and setters.

Now let’s go ahead and create the test for this Model.

Unit test getters and setters

Under the tests/Unit/Models namespace create the UserTest.php file.

To make the code cleaner and easier to use, create the setUp() method for this test in which we instantiate the User model.

The tests are simple and pretty straightforward.

We set the value of a specific attribute and then we check if the value we just set corresponds with the value of the getter.

I hope you now have a clearer view of how you can test a Model’s getters and setters.

You can use what you’ve learned in this post to create even more advanced unit tests if your Models have a more complicated logic in getters and setters.


Let me know what you think about this article through comments below, or on Twitter at @pelu_carol.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.


You may also like...