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

时间:2016-11-09 05:58:52

标签: php unit-testing

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

我正在尝试模拟一种方法。在执行测试用例时,mocked方法没有调用。相反,我尝试使用系统定义的方法,它正如预期的那样正常工作。

请参阅以下代码:

/* 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'没有被触发。

我可以知道原因吗? 有人请帮帮我。如果您想了解更多详情,请告诉我。

提前致谢...

1 个答案:

答案 0 :(得分:0)

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

return $that->mockTestCall();
相关问题