【问题标题】:How to check that method of a mockobject was not called only with a specific parameter?如何检查模拟对象的方法不是仅使用特定参数调用的?
【发布时间】:2015-05-13 16:34:09
【问题描述】:

我有一个PHPUnit_Framework_MockObject_MockObject 和一个Logger

在单元测试中,我不希望使用特定的字符串参数 doNotCallMeWithThisString 调用 warn 方法。

我已经走到这一步了:

public function testThis()
{
    ...

    $logger = $this->getMockLogger();
    $logger->expects($this->exactly(0))->method('warn')->with(
        $this->equalTo('doNotCallMeWithThisString')
    );
    ...
}

但这失败了,因为exactly(0) 将对warn 方法的任何调用标记为错误,即使字符串参数是somethingEntirelyUnrelated

我如何告诉模拟对象对warn 的任何调用都可以,除非它是使用特定字符串调用的?

【问题讨论】:

    标签: php unit-testing mocking phpunit


    【解决方案1】:

    exactly() 方法用于断言模拟方法将被调用多少次。除非您将 $this->at() 用于模拟行为,否则不要为特定调用指定参数。 exactly(0) 说调用次数应该是0。

    将您的模拟更改为:

     $logger->expects($this->any()) //Or however many times it should be called
            ->method('warn')
            ->with(
                  $this->callback(function($argument) {
                      return $argument !== 'doNotCallMeWithThisString';
                  })
             )
     );
    

    这使用回调来检查传递给模拟方法的参数并验证它不等于您的字符串。

    The PHPUnit documentation has the constraint types that you can use to verify the arguments of a mock.此时没有字符串不等于类型。但是使用回调,您可以自己制作。您的回调只需要检查使用的参数,如果正常则返回true,否则返回false

    【讨论】:

      【解决方案2】:

      您可以使用callback 断言。这样,每次调用参数时都会调用您提供的回调方法:

      $logger
          ->expects($this->any())
          ->method('warn')
          ->with($this->callback(function($string) {
              return $string !== 'doNotCallMeWithThisString';
          }));
      

      关于此的一些要点:

      1. 由于您实际上并不关心多久调用该方法(或者是否调用它),只要它没有使用错误参数调用,您需要使用 $this->any() 作为调用计数匹配器。
      2. 每次调用模拟方法都会调用回调约束。它必须返回 TRUE 才能匹配约束。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-13
        • 1970-01-01
        • 2019-07-17
        • 2018-08-31
        • 2016-06-08
        • 2014-09-26
        • 1970-01-01
        相关资源
        最近更新 更多