PHPUnit is a Framework designed to write unit tests in the PHP programming language. It belongs to the family of unit tests that are built on the xUnit architecture.
The purpose of PHPUnit
PHP unit is based on the assumption that developers should be able to find errors in their freshly committed codes quickly and assess that there has been no code deterioration in other sections of the code base. As in other frameworks for unit tests, PHPUnit uses assertion to verify that the behaviour of a tested specific component – of a “unit” - meets expectations.
The point of the unit testing is to isolate different parts of the programme and to show that these individual parts are correct. The unit tests offer a strict written commitment that the part of the code must fulfil. The result is that errors are found at an earlier stage of the development cycle.
PHPUnit can display test results in many different formats, including Junit XML or TestDox.
To remove the complications it brings when a developer tries to test software that needs to be integrated through a Web site, this Framework uses the command line. This allows individual classes to be tested deep before they are integrated together.
Key PHPUnit concepts
Assertion. Assertion adds to the test the criterion by which the code is checked to fulfil its role.
Stub. If a part of the code depends on an external object, it is possible to use stub that has the role of a double of this external objects. This allows you to concentrate on this specific part of the code only when testing.
Mock. Mock works like a stub, but checks whether the external object has received appropriate requests from the tested code.
Annotation. Unique type of syntactic metadata that can be added to the code written in PHP. It is used to describe the source code, for example it can define, which methods are to be called after each test method in the test class.
The advantages of using PHPUnit
Reduction of the development time. PHPUnit helps to find mistakes in an earlier stage of the development cycle. These are both code errors and missing parts of the code unit specification.
Facilitating of a change. Code changes are normally risky. PHPUnit tests make it possible to verify that the modules still work as they are supposed to.
Simplification of the integration. PHPUnit testing can reduce uncertainty in individual units and can thus be used to test from the bottom. Testing the different parts of the programme and subsequently testing the code subgroups leads to the facilitation of subsequent integration testing.
The disadvantages of using PHPUnit
Risk of using mocks. The use of mocks makes it possible to mock protected methods, to call non-existent methods and mocks don’t react to unexpected calls from test doubles. Therefore, the use of PHPUnit can lead to the hacking of objects rather than to the design of a consistent and functional code.