This is part 3 of PHPUnit Beginner. In this tutorial we will explain when and how to use test doubles in our test.
As mentioned in the first part of this series. One of PHPUnit's powerful features is test double. It is very common in our code, a function of one class is calling another class's function. In this case, we have a dependency in these two classes. In particular, the caller class has a dependency on calling class. But as we already know in part 1, unit test should test the smallest unit of functionality, in this case, it should test only the caller function. To solve this problem, We can use test double to replace the calling class. Since a test double can be configured to return predefined results, we can focus on testing the caller function.
Test double is a generic term for objects we use, to replace real production ready objects. In our opinion, it is very useful to categorize test doubles by their purpose. It does not only make it easy for us to understand the test case, but also make our code friendly to other parties.
Accordingly to Martin Fowler's post, There are five types of test double:
PHPUnit's method getMockBuilder can be used to create any similar user defined objects. Combining with its configurable interface. We can use it to create basically all five types of test doubles.
It is meaningless to use test double to our calculator test case, since currently the Calculator class has no dependency on other classes. However to demonstrate how to use test double in PHPUnit, we will create a stub Calculator class and test it.
Let's add a test case called testWithStub to our existing class:
public function testWithStub()
{
// Create a stub for the Calculator class.
$calculator = $this->getMockBuilder('Calculator')
->getMock();
// Configure the stub.
$calculator->expects($this->any())
->method('add')
->will($this->returnValue(6));
$this->assertEquals(6, $calculator->add(100,100));
}
We have completed the PHPUnit Beginner series. You should have gained enough knowledge on PHPUnit to start implementing unit tests on your code. If you are looking for more, checkout the The Grumpy Programmer's PHPUnit Cookbook.
Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.