PHP单元测试:模拟方法在执行测试用例时不会被触发


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

我正在为Zend框架的单元测试开发测试用例。使用composer安装了PHPUnit。我在Windows平台上工作。

我正在尝试模拟一个方法。在执行测试用例时,被模拟的方法没有调用。相反,我尝试了系统定义的方法,它像预期的那样工作良好。

请参见下面的代码:

/* 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'));
    }
}

在执行上述代码时,测试用例方法'testReturnCallbackStubSystem'按预期工作。
但是测试用例方法'testReturnCallbackStub'不工作。这里模拟的方法'mockTestCall'没有被触发。

我可以知道原因吗?谁来帮帮我吧。如果你想知道更多的细节,请告诉我。

我无法测试,但我认为你应该使用

return $that->mockTestCall();