【问题标题】:PHPUnit Mockup issuePHPUnit 样机问题
【发布时间】:2016-12-21 11:50:13
【问题描述】:

我有一个服务类的模型。 在我的setUp 函数中是这样定义的

$this->myServiceMockup = $this->getMockBuilder(MyService::class)
            ->disableOriginalConstructor()
            ->setMethods(['myMethod'])
            ->getMock();

在我的测试函数中,我对它设定了这样的期望。

$this->myServiceMockup->expects($this->once())
            ->method('myMethod')
            ->with($this->exactly(1), 'myName')
            ->willReturn($this->exactly(1));

所以这意味着当我应该只触发一次 myMethod 函数并且它将返回整数 1。

所以我正在测试的方法有那行代码。

$myIntValue = $this->myService->myMethod($number, $name);

$myIntValue 这一行之后,当我运行测试时,测试应该是 1 并且测试应该继续,这就是我对此的理解。

但是我得到了这个错误

方法名称的期望失败等于何时 调用1次参数0调用

My\Path\To\Class\MyService::myMethod(1, 'myName') 不匹配 期望值。

1 与预期类型“对象”不匹配。

没有任何意义,因为myMethod 需要一个整数和一个字符串。

public function myMethod($number, $name)
{
    return $this->table->save($number, $name);
}

有人可以向我解释我在这里做错了什么,因为我没有想法。

【问题讨论】:

    标签: php mocking phpunit


    【解决方案1】:

    exactly() 是一个调用计数匹配器(如once()any()),用作expects() 方法的参数。

    只需替换:

    ->with($this->exactly(1), 'myName')
    

    ->with(1, 'myName')
    

    willReturn() 也“按原样”接受值。

    【讨论】:

      【解决方案2】:

      你没有正确使用$this->with

      $this->myServiceMockup
          ->expects($this->once())
          ->method('myMethod')
          ->with($this->equalTo(1), $this->stringContains('myName'))
          ->willReturn(1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-12
        • 2017-09-25
        • 2019-11-22
        • 1970-01-01
        相关资源
        最近更新 更多