Tests

Unit

A unit test is the smallest testable part of an application like functions, classes, procedures, interfaces. Unit testing is a method by which individual units of source code are tested to determine if they are fit for use.

What is the smallest testable part of the dummy application, which is responsible for the product addition functionality? It’s the ProductController::add method! Even though we don’t make a real HTTP request and don’t have a database connection, we can still check if the method has expected behaviour.

To make sure that a product is saved in the database, we only need to test whether the EntityManager::persist method is invoked or not. When we provide valid form values in the request, we expect the persist method to be called, otherwise it must not be triggered:

In the test case above we defined two data sets: one contains a list of valid form values and another - invalid values. Then we described the EntityManager mock behaviour for every possible input to verify, that we correctly process a product in each case.

Generally, it’s a good idea to separate Unit from Integration tests. That’s why we’ve created the test in the Unit namespace and declared dedicated test suites in phpunit.xml.dist:

This setup allows us to run Unit and Integration test independently. Let’s leverage the power of PHP-FPM image (that we’ve created in the first part of the series) to start the tests:

After executing the command above, you should see the following output in the terminal: