dongsong73032 2017-12-25 12:23
浏览 171
已采纳

PHPUnit:如何通过测试方法模拟内部调用的函数

In the below example, I want to mock the calling of getBaseValue() inside the multipliedValue(). But I cannot figure it out.

class Sample
{
    function multipliedValue()
    {
      $value = $this->getBaseValue();
      return $value * 2;
    }

    function getBaseValue()
    {
      return 2;
    }
}

I have used PHPUnit mocking, but it didn't work. So, I used the following code:

class SampleTest extends PHPUnit_Framework_TestCase
{
  function testMultipliedValueIfBaseValueIsFalse()
  {
        $mockedObject = $this->getMockBuilder(Sample::class)
            ->setMethods(['multipliedValue', 'getBaseValue'])
            ->getMock();
        $mockedObject->expects($this->any())
            ->method("getBaseValue")
            ->willReturn(false);
        $result = $mockedObject->multipliedValue();
        $this->assertFalse($result);
  }
}

I tried to create a global function, but only force one of the method to return my desired value, the rest just go as they are. How should I approach this test?

The error I am currently getting is for the $this in the multipliedValue() method, which treats it as the stubbed object.

  • 写回答

1条回答 默认 最新

  • donglu6303 2017-12-25 12:43
    关注

    All the methods listed in the ->setMethods() will be stubbed and return null by default so if you only want to stub getBaseValue then do:

    $mockedObject = $this->getMockBuilder(Sample::class)
            ->setMethods(['getBaseValue'])
            ->getMock();
        $mockedObject->expects($this->any())
            ->method("getBaseValue")
            ->willReturn(false);
        $result = $mockedObject->multipliedValue();
        $this->assertFalse($result);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 powerbuilder出现这样的报错
  • ¥15 h3.6m 人类行为预测论文复现
  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因
  • ¥20 linxu服务器僵尸进程不释放,代码如何修改?
  • ¥15 pycharm激活不成功
  • ¥40 如果update 一个列名为参数的value
  • ¥15 基于51单片机的水位检测系统设计中LCD1602一直不显示
  • ¥15 OCS2安装出现问题,请大家给点意见
  • ¥15 ros小车启动launch文件报错
  • ¥15 vs2015到期想登陆但是登陆不上