【问题标题】:PHPUnit assert mock method with multiple stringContains for one parameterPHPUnit 为一个参数断言具有多个 stringContains 的模拟方法
【发布时间】:2014-05-05 13:43:52
【问题描述】:

有没有办法为多个匹配断言模拟类方法字符串参数?

$this->getMock()
     ->expects($this->any())
     ->method('setString')
     ->with($this->stringContains('word3'))
     ->will($this->returnSelf());

这个例子将通过 ->setString('word1 word2 word3 word4')

我需要做的是匹配是否使用包含“word1”和“word3”的参数调用 setString()

但是

$this->getMock()
     ->expects($this->any())
     ->method('setString')
     ->with(
         $this->stringContains('word1'),
         $this->stringContains('word3')
     )
     ->will($this->returnSelf());

这个实现正在检查 setString() 的 2 个参数,这不是我想要检查的。

想法?使用 $this->callback() ?有没有更适合的 PHPUnit 断言?

【问题讨论】:

标签: php unit-testing phpunit


【解决方案1】:

我知道这个答案已经很晚了,但我遇到了同样的问题,并找到了一个似乎更聪明的解决方案...... :)

试试这个:(未针对您的情况进行测试)

$this->getMock()
     ->expects($this->any())
     ->method('setString')
     ->with($this->logicalAnd(
          $this->stringContains('word1'),
          $this->stringContains('word3')
      ))
     ->will($this->returnSelf());

【讨论】:

    【解决方案2】:

    我想这会满足您的要求:

    $this->getMock()
    ->expects($this->any())
    ->method('setString')
    ->with(
        $this->callback(
            function($parameter) {
                $searchWords = array('word1', 'word3');
                $matches     = 0;
    
                foreach ($searchWords as $word) {
                    if (strpos($parameter, $word) !== false) {
                        $matches++;
                    }
                }
    
                if ($matches == count($searchWords)) {
                    return true;
                } else {
                    return false;
                }
            }
    ))
    ->will($this->returnSelf());
    

    回调函数检查 $searchWords 数组中的两个值是否都是传递给 setString() 方法的第一个参数的一部分。

    【讨论】:

      猜你喜欢
      • 2011-07-25
      • 2017-03-01
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 2020-02-17
      • 2013-04-16
      相关资源
      最近更新 更多