Introduction to Mock
When we unit test Class A, Class A may depend on Class B. In order to reduce dependencies and facilitate testing of Class A methods, we can simulate a Class B and simply specify the return values of each method (instead of actually implementing the specific logic).
Phpunit provides a set of simulation APIs, which are simply used as follows:
class StubTest extends PHPUnit_Framework_TestCase
{
public function testStub()
{
// Create a stub for the SomeClass class.
$stub = $this->getMock(‘SomeClass’);
// Configure the stub.
$stub->expects($this->any())
->method(‘doSomething’)
->will($this->returnValue(‘foo’));
// Calling $stub->doSomething() will now return ‘foo’.
$this->assertEquals(‘foo’, $stub->doSomething());
}
}
In this example, we get a simulation of 'SomeClass', which can be called any number of times. If the doSomething method is called, the value foo will be obtained.
Two Questions
We know that for a singleton class, its constructor method is private, and the implementation of getMock calls the constructor method of the original class by default.
If SomeClass is a singleton, phpunit will prompt
Call to private SomeClass::__construct() from context ‘PHPUnit_Framework_TestCase’
At this time, how should we conduct our test?
Three solutions
Still use getMock for mocking.
Just set its fifth parameter to false. What it means is: Do not call the constructor of the original object.
$stub = $this->getMock(‘SomeClass’, array(), array(), ”, false);
I have to say, this is a bit complicated to use.
If you are using phpunit3.5 and above, there is an easier-to-use API. You can disable calls to the original constructor method like this:
$stub=$this->getMockBuilder(‘SomeClass’)->disableOriginalConstructor()->getMock();
Attachment:
For a detailed explanation of the six optional parameters of getMock, see: http://www.phpunit.de/manual/3.6/en/test-doubles.html
The manual does not mention their default values. After testing, the results are as follows, posted here for everyone’s convenience.
array(), array(), ”, false, false, false
That is
$stub=$this->getMockBuilder(‘SomeClass’)
Equivalent to:
$stub=$this->getMockBuilder(‘SomeClass’, array(), array(), ”, true, false, false)