Test and organize your code with unit tests

The principle of a unit test is very simple: it involves running code from the application to test and verifying that everything went as planned. The purpose of a unit test is to allow A php developer to ensure that a unit of code does not have a programming error. So, a test is a program that executes the code of a class to ensure that it is correct, that is, its results match what is expected in predefined assertions.

Basic notions of unitary tests

In general, a test is broken down into three parts, following the pattern "AAA", which corresponds to the words "Arrange, Act, Assert".

  • Arrange: The first step is to define the objects, the variables necessary for the proper functioning of its test (initialize the variables, initialize the objects to pass into parameters of the method to be tested, etc.).

  • Act: Then, it is to execute the action that one wishes to test (in general, to execute the method that one wants to test, etc.)

  • Assert: And finally to verify that the result obtained is in line with our expectations.

Unit tests have the most effect on code quality when they are part of the workflow of your software development. As soon as you write a function or other block of application code, create unit tests to check the behavior of the code in response to the standard, limit and incorrect cases of the input data, as well as the explicit or implicit assumptions of the code . With test-driven development, as you create unit tests before writing code, you use unit tests as design documentation and functional specifications.

You can quickly generate test projects and test methods from your code, or manually create tests whenever you want.

So, there are many ways to do tests. The one that seems most natural is the one that is done manually. We launch its application, we click everywhere, we look if it works. When the tests cover all the scenarios of a code, we can ensure that our code works. In addition, it allows maintenance operations on the code while being certain that this code will not have undergone regressions.

See our news