boots
boots

Reputation: 301

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 else in classB, just this one method.

Upvotes: 1

Views: 878

Answers (2)

David Harkness
David Harkness

Reputation: 36562

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() ...
}

Upvotes: 2

Spidy
Spidy

Reputation: 40002

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"

Upvotes: 0

Related Questions