[英]How to test that only specific methods of a mock were called with PHPUnit
I have a class I want to mock and make sure that only one of its methods was called. 我有一个要模拟的类,并确保仅调用了其中一个方法。 How can I construct such a mock object in PHPUnit?
如何在PHPUnit中构造这样的模拟对象? Something like
就像是
public function testSystemUnderTestOnlyInvokesFoo() {
$myMock = $this->createMock(ClassWithManyMethods::class);
$myMock->expects($this->once())->method('foo');
// Something like this
// $myMock->expects($this->never)->method($this->anyMethodExcept('foo'))
function_under_test($myMock);
}
The method
function accepts both a string and a Constraint
class. method
函数同时接受字符串和Constraint
类。 A PHPUnit test can create constraint classes with utility functions like isNull
, contains
or matches
. PHPUnit测试可以创建带有实用函数(如
isNull
, contains
或matches
约束类。 In the example, anyMethodExcept
translates to code like this: 在示例中,
anyMethodExcept
转换为如下代码:
public function testSystemUnderTestOnlyInvokesFoo() {
$myMock = $this->createMock(ClassWithManyMethods::class);
$myMock->expects($this->never)
->method($this->logicalNot($this->matches('foo')));
$myMock->expects($this->once())->method('foo');
function_under_test($myMock);
}
If you have several methods you want to exclude, use matchesRegex
like this: 如果您有几种方法要排除,请使用
matchesRegex
像这样:
$myMock->expects($this->never)
->method($this->logicalNot($this->matchesRegex('/foo|bar|baz/')));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.