How to simulate (mock) a singleton class in phpunit. A Mock introduction when we perform A unit test on Class A, Class A may depend on Class B. to reduce the dependency and facilitate the test of Class A methods, we can simulate A Class B, briefly stipulate all parties
1 Mock introduction
When we perform A unit test on Class A, Class A may depend on Class B. to reduce the dependency and facilitate the test of Class A method, we can simulate A Class B, specify the return values of each method (rather than the actual implementation logic ).
Phpunit provides a set of simulation class APIs, which are easy to use 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 ', specifying that it can be called any time. if the doSomething method is called, the value foo is obtained.
Problem 2
We know that for a singleton class, the constructor method is private, while the implementation of getMock is to call 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'
How can we perform the test?
Solution 3
Still use getMock for simulation.
Set the 5th parameters to false. It means that the constructor of the original object is not called.
$ Stub = $ this-> getMock ('someclass ', array (), array (), ", false );
I have to say that this is a bit complicated to use.
If you are using phpunit3.5 or a later version, you can use more easy-to-use APIs. You can disable calling the original constructor method as follows:
$ Stub = $ this-> getMockBuilder ('someclass ')-> disableOriginalConstructor ()-> getMock ();
Appendix:
For details about the six optional parameters of getMock, see: http://www.phpunit.de/manual/3.6/en/test-doubles.html
Their default values are not mentioned in the manual. the test results are as follows.
Array (), array (), ", false
That is
$ Stub = $ this-> getMockBuilder ('someclass ')
Equivalent:
$ Stub = $ this-> getMockBuilder ('someclass ', array (), array (), ", true, false, false)
Mock introduction when we perform A unit test on Class A, Class A may depend on Class B. to reduce the dependency and facilitate the test of Class A methods, we can simulate A Class B, briefly stipulate the parties...