断言:
$chain->expects($this->once())
->method('addMethodCall')
->with(
'addOptionsProvider',
array(
$this->isInstanceOf('Symfony\Component\DependencyInjection\Reference'),
$this->equalTo(7)
)
);
$chain
实际上是 Definition
的模拟对象,这是我要测试的代码:
$definition->addMethodCall(
'addOptionsProvider',
array(new Reference($id), $priority)
);
我刚开始使用 PHPUnit,所以我真的不知道我错过了什么。我发现断言论点真的很难理解。我已经包含了一个图像,其中包含断言和实际参数之间的视觉差异。
PHPUnit_Framework_ExpectationFailedException : Expectation failed for method name is equal to when invoked 1 time(s) Parameter 1 for invocation Symfony\Component\DependencyInjection\Definition::addMethodCall('addOptionsProvider', Array (...)) does not match expected value.
编辑:实际上,我最终得到了这个:
$chain->expects($this->once())
->method('addMethodCall')
->with(
$this->identicalTo('addOptionsProvider'),
$this->logicalAnd(
$this->isType('array'),
$this->arrayHasKey(0),
$this->arrayHasKey(1)
)
);
但我不能“进入”数组值以进行进一步断言!
最佳答案
->with()
的方法签名与您预期的不同。
->with(string|PHPUnit_Framework_Constraint, ...)
这意味着您不能只向其中传递一个数组,因为 PHPUnit 不够“智能”,无法理解您的意思。
模拟这个的最简单方法应该是:
->with(
'addOptionsProvider',
array(
new Reference(1),
7
)
)
因为它只会比较数组。
另一种模拟这个的方法(如果你需要对对象进行方法调用等等)是使用
->with($this->callback(function($arg) { ... } ));
并在那里做出你的断言。
有关复杂示例,请参阅:mock atLeastOnce with concrete value, the rest not important
关于php - 无法断言 PHPUnit 中的参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13962206/