PHPUnit test doubles

二次信任 提交于 2021-02-16 18:53:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!