php 如何在 PHPUnit 模拟对象中测试第二个参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/311485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:21:15  来源:igfitidea点击:

How to test a second parameter in a PHPUnit mock object

phpphpunit

提问by Joel

This is what I have:

这就是我所拥有的:

$observer = $this->getMock('SomeObserverClass', array('method'));
$observer->expects($this->once())
         ->method('method')
         ->with($this->equalTo($arg1));

But the method should take two parameters. I am only testing that the first parameter is being passed correctly (as $arg1).

但是该方法应该采用两个参数。我只是测试第一个参数是否正确传递(作为 $arg1)。

How do test the second parameter?

如何测试第二个参数?

回答by silfreed

I believe the way to do this is:

我相信这样做的方法是:

$observer->expects($this->once())
     ->method('method')
     ->with($this->equalTo($arg1),$this->equalTo($arg2));

Or

或者

$observer->expects($this->once())
     ->method('method')
     ->with($arg1, $arg2);

If you need to perform a different type of assertion on the 2nd arg, you can do that, too:

如果您需要对第二个参数执行不同类型的断言,您也可以这样做:

$observer->expects($this->once())
     ->method('method')
     ->with($this->equalTo($arg1),$this->stringContains('some_string'));

If you need to make sure some argument passes multiple assertions, use logicalAnd()

如果您需要确保某个参数通过多个断言,请使用 logicalAnd()

$observer->expects($this->once())
     ->method('method')
     ->with($this->logicalAnd($this->stringContains('a'), $this->stringContains('b')));