greg greg -4 years ago 169
PHP Question

phpunit testing method that calls other class methods which need mock

I'm trying to create a pretty standard unit test where I call a method and assert it's response, however the method I'm testing calls another method inside the same class which does a little bit of heavy lifting.

I want to mock that one method but still execute the method I'm testing as is, only with the mocked value returned from the call to the other method.

I've dumbed down the example to make it as simple as possible.

class MyClass

// I want to test this method, but mock the handleValue method to always return a set value.

public function testMethod($arg)

$value = $arg->getValue();



// This method needs to be mocked to always return a set value.

public function handleValue($value)

// Do a bunch of stuff...
$value += 20;

return $value;



My attempt at writing the tests.

class MyClassTest extends \PHPUnit_Framework_TestCase

public function testTheTestMethod()

// mock the object that is passed in as an arg
$arg = $this->getMockBuilder('SomeEntity')->getMock();

// test handle document()
$myClass = new MyClass();

$result = $myClass->testMethod($arg);

// assert result is the correct
$this->assertEquals($result, 50);



I have tried mocking the MyClass object, but when I do that and call the testMethod it always returns null. I need a way to mock the one method but leave the rest of the object intact.

Answer Source

You can mock the class that you are testing and specify the method that you want to mock.

$mock = $this->getMockBuilder('MyClass')

    ->will($this->returnValue(23)) //Whatever value you want to return

However, IMO this is not the best idea for your tests. Testing like this will make refactoring much more difficult. You are specifying the implementation of the class rather than the behavior that the class is supposed to have. If handleValue is doing a lot of complicated work that makes testing difficult, consider moving the logic into a separate class and injecting that into your class. Then you can create a mock of that class and pass it in to testMethod. Doing so will give you the added advantage of making MyClass more extensible if handleValue needs to adapt its behavior.

As a general rule, you should not mock the system that you are testing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download