a mock introduction
When we do unit tests on Class A, the class A May be dependent on class B, in order to reduce dependency and facilitate the test of class A methods, we can simulate a class B to simply specify the return value of each method (rather than actually implementing the specific logic).
The PHPUnit provides a set of simulation-class APIs that are simple to use:
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 () would now return ' Foo '.
$this->assertequals (' foo ', $stub->dosomething ());
}
}
In this example, we get a ' someclass ' simulation that specifies that it can be called any time, and if the DoSomething method is called, it will get the value foo.
Two questions
We know that for a singleton class, its constructor method is private, and Getmock's implementation, by default, is to invoke the constructor method of the original class.
If SomeClass is a singleton, PHPUnit will prompt
Call to Private someclass::__construct () from context ' phpunit_framework_testcase '
At this point, how should our tests proceed?
Three Solutions
Simulations are still performed using Getmock.
Just set its 5th parameter to False. The implication is that the constructor of the original object is not called.
$stub = $this->getmock (' SomeClass ', Array (), array (), ", false);
I have to say, it's a bit complicated to use.
If you're using phpunit3.5 and above, there's an easier-to-use API. You can disable the invocation of the original constructor method in this way:
$stub = $this->getmockbuilder (' SomeClass ')->disableoriginalconstructor ()->getmock ();
Report:
For a detailed description of the 6 optional parameters of Getmock, see: http://www.phpunit.de/manual/3.6/en/test-doubles.html
The manual does not mention their default values, the test results are as follows, posted to facilitate the use of everyone.
Array (), array (), ", False, False, False
That
$stub = $this->getmockbuilder (' SomeClass ')
Equivalent to:
$stub = $this->getmockbuilder (' SomeClass ', Array (), array (), ", True, False, False)
http://www.bkjia.com/PHPjc/478025.html www.bkjia.com true http://www.bkjia.com/PHPjc/478025.html techarticle A mock introduction when we do unit tests on Class A, class A May depend on class B, in order to reduce dependence and facilitate the testing of class A methods, we can simulate a class B and simply stipulate its parties ...