开发者

Mock a single function call in another class

classA::getValue() calls a method in another class, classB::verifyValue(). Since classB::verifyValue() has external dependencies, I want to be able to mock it to simply return true inside my unit test.

I don't want to touch anything els开发者_开发技巧e in classB, just this one method.


You can create a test stub as Spidy suggests or you can use PHPUnit's built-in mock objects. Both require that you be able to provide the classB instance for classA to use.

function testGetValue() {
    // set up mock classB
    $b = $this->getMock('classB', array('verifyValue'));
    $b->expects($this->once())
      ->method('verifyValue')
      ->will($this->returnValue(true));

    // set up classA
    $a = ...
    $a->setClassB($b);

    // test getValue()
    ... $a->getValue() ...
}


Use interfaces and a MockClassB in your test. For example, interfaceB has verifyValue(). So classB implements interfaceB and overrides verifyValue. Then you create another class called MockClassB and have it also implement interfaceB. In your test code, rather then creating classB, create MockClassB (MockClassB will return true rather then relying on external dependencies).

If that doesn't make enough sense, look up "programming to an interface, not an implementation"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜