Tips for writing easy-to-write unit tests in Laravel

Tram Ho


Unit tests are no stranger to everyone. It is mainly written to test the designed functions as well as covering all the lines of code in the project and in turn to ensure project quality. But how to write code to write unit tests easily is also one of the issues of concern.
So today I will introduce you to the tips to write code in laravel to easily write unit tests that I have learned in the past.
(In this article, by default, you already know how to write basic unit tests.)


1. Load external classes in the class into __construct ()

When creating a class, if inside the class, we use other classes from the outside instead of calling directly like this for fast:

Then we will do the following: All external classes are used, we will add them to construct () in the class:


Reason : When we do not add but call directly, when writing unit tests for the Test class, it is very difficult to use Mockery to mock the outer classes and set the methods to return the value needed for it ==> manual it is difficult to write unit tests for that function (sometimes it may seem even impossible to write).

2. Limit the use of the private function, private, static, final

For example:

Looking at the above code in the private testA function call to the private testB function (or static testC) actually writing unitest mock function testB (or static testC) to return a certain value is also very difficult. Because the nature of unit testing is that when testing A function that uses external classes, we will isolate and mock those classes to return the values ​​we want. Therefore, above we cannot mock the function testB nor testC to use the results when writing unit tests for function testA. (You can click here to read more with the following paragraph)

3. 1 function should be at most 30-40 lines

As well as writing standard code, a function should have a maximum of 30-40 lines but in fact many of you do not pay much attention to it, so when writing the number of lines in a function up to 200-300 lines. Actually when you read the code yourself or others read the code you are also a nightmare. The case is to write a test for it.

4. Always return the value for the function

A function should have a return result so we can write a unit test more accurately or correctly instead of nothing (sometimes coverage will only pass through the code and use assertNull is a bit pointless. 😃 )).


Above are the experiences that I have learned during the writing process of unit testing in my laravel.

Hope to help you.

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo