Sreejith Pm Sreejith Pm - 1 month ago 8
PHP Question

PHP Unit Testing: Mocked methods are not getting triggered while executing the test case

I am developing test cases for Unit Testing with Zend framework. Installed PHPUnit using composer. I am working on Windows platform.

I am trying to mock a method. While executing the test case, mocked method is not invoking. Instead I tried with system defined method, it is working fine as expected.

Please see below code:

/* Class CommonDataHandlerTest */
class CommonDataHandlerTest extends PHPUnit_Framework_TestCase{
public function mockTestCall(){
return 'foo';
}
}


class Apps_Sample_DataHandlerTest extends CommonDataHandlerTest{
public function setUp() {
....
}

public function tearDown() {
....
}

/*But here the method mockTestCall is not triggering while executing */
public function testReturnCallbackStub() {

$observer = $this->getMockBuilder('Apps_Sample_DataHandler')
->disableOriginalConstructor()
->disableOriginalClone()
->disableArgumentCloning()
->getMock();


$that = $this;
$observer->method('getSampleData')
->will($this->returnCallback(
function() use($that) {
$that->mockTestCall();
}
));


$this->assertEquals('foo', $observer->getSampleData());
}

/*This is method is working as expected*/
public function testReturnCallbackStubSystem() {

$observer = $this->getMockBuilder('Apps_Sample_DataHandler')
->disableOriginalConstructor()
->disableOriginalClone()
->disableArgumentCloning()
->getMock();


$observer->method('getSampleData')
->will($this->returnCallback('str_rot13'));


$this->assertEquals('foo', $observer->getSampleData('ssb'));
}

}


While executing the above code, the test case method 'testReturnCallbackStubSystem' is working as expected.

But the test case method 'testReturnCallbackStub' is not working. Here the mocked method 'mockTestCall' is not getting triggered.

May I know the reason please?
Somebody please help me on this. If you want if any more details, please let me know.

Thanks in advance...

Answer

I could not test but I think you should use

return $that->mockTestCall();