断言:
$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:期望失败 方法名称等于1次调用时间 参数1用于调用 Symfony的\分量\ DependencyInjection \定义:: addMethodCall( 'addOptionsProvider', 数组(...))与期望值不匹配。
编辑:实际上,我最终得到了这个:
$chain->expects($this->once())
->method('addMethodCall')
->with(
$this->identicalTo('addOptionsProvider'),
$this->logicalAnd(
$this->isType('array'),
$this->arrayHasKey(0),
$this->arrayHasKey(1)
)
);
但是我不能“进入”数组值以进行进一步的断言!
答案 0 :(得分:2)
->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