问题
I am starting to use PHPUnit for test my code but I have some problems with understand double tests.
I try to stub a class method b to return true instead of usual behavior (false) when is called since another method
I have a code like this
class MyClass {
function a()
{
return $this->b();
}
function b()
{
return false;
}
}
class MyClassTest extends TestCase
{
function testAThrowStubB()
{
$myClassStub = $this->getMockBuilder('\MyClass')
->getMock();
$myClassStub->expects($this->any())
->method('b')
->willReturn(true);
// this assert will work
$this->assertTrue($myClassStub->b());
// this assert will fail
$this->assertTrue($myClassStub->a());
}
}
I thought my second assertion will work but it doesn't. I'm wrong and it is not possible? There is another way to test a function who depends on another overriding his behavior?
Thanks
回答1:
When you mock a class the PHPUnit framework expects that you're mocking the entire class. Any methods for which you don't specify any return values will default to returning null
(which is why the second test was failing).
If you want to mock a subset of methods use the setMethods
function:
$myClassStub = $this->getMockBuilder(MyClass::class)
->setMethods(["b"])
->getMock();
$myClassStub->expects($this->any())
->method('b')
->willReturn(true);
// this assert will work
$this->assertTrue($myClassStub->b());
// this assert will work too
$this->assertTrue($myClassStub->a());
This is noted in the documentation in example 9.11
来源:https://stackoverflow.com/questions/46192311/phpunit-test-doubles