【问题标题】:Mocking public method of testing object模拟测试对象的公共方法
【发布时间】:2015-02-24 05:30:36
【问题描述】:

我有一个有两个公共方法的类。它看起来像下面这样:

class IntRequest
{
    public function updateStatus()
    {
        $isValid = $this->checkValidity();

        // ... next is a complex logic that use $isValid
    }

    /**
     * @return bool
     */
    public function isValid()
    {
        // another complex logic
    }
}

我需要测试第一个函数 - IntRequesr::updateStatus;但是我需要运行测试。第一个带有IntRequests::isValid 的返回false,第二个带有true 作为IntRequests::isValid 的结果

我尝试模拟该函数,但测试运行时调用实际的 IntRequests::isValid 而不是模拟的。

我的测试代码是

$intRequest = new IntRequests;

$mock = m::mock($intRequest);
$mock->shouldReceive('isValid')
    ->once()
    ->andReturn(true);

$res = $mock->updateStatus();

$this->assertTrue($res);

我尝试拨打$res = $intRequest->updateStatus() 而不是$res = $mock->updateStatus(),但没有成功。

所以,我想知道是否可以模拟在测试方法中调用的函数?

【问题讨论】:

    标签: php unit-testing testing phpunit mockery


    【解决方案1】:

    你需要一个partial mock(一个模拟对象,其中一些方法被存根,而其余的保持原样)。由于我只使用 phpunit 自己的模拟库这样做,我只能将您指向文档,但似乎您应该将 ->makePartial() 添加到您的模拟实例化中

    【讨论】:

      猜你喜欢
      • 2015-12-17
      • 2014-06-07
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      相关资源
      最近更新 更多