【发布时间】:2010-03-22 22:32:37
【问题描述】:
我正在为 Foo 类构建单元测试,而且我对单元测试还很陌生。
我的类的一个关键组件是BarCollection 的一个实例,它包含许多Bar 对象。 Foo 中的一个方法遍历集合并在集合中的每个 Bar 对象上调用几个方法。我想使用存根对象为我的测试类生成一系列响应。如何让Bar 存根类在迭代时返回不同的值?我正在尝试按照以下方式做一些事情:
$stubs = array();
foreach ($array as $value) {
$barStub = $this->getMock('Bar');
$barStub->expects($this->any())
->method('GetValue')
->will($this->returnValue($value));
$stubs[] = $barStub;
}
// populate stubs into `Foo`
// assert results from `Foo->someMethod()`
所以Foo->someMethod() 将根据从Bar 对象接收到的结果生成数据。但是,只要数组长于一个,这就会给我以下错误:
There was 1 failure:
1) testMyTest(FooTest) with data set #2 (array(0.5, 0.5))
Expectation failed for method name is equal to <string:GetValue> when invoked zero or more times.
Mocked method does not exist.
/usr/share/php/PHPUnit/Framework/MockObject/Mock.php(193) : eval()'d code:25
我的一个想法是使用->will($this->returnCallback()) 调用回调方法,但我不知道如何向回调指示哪个Bar 对象正在进行调用(以及因此给出什么响应)。
另一个想法是使用onConsecutiveCalls() 方法或类似方法,告诉我的存根第一次返回 1,第二次返回 2,依此类推,但我不确定如何执行此操作。我还担心,如果我的班级除了对集合进行有序迭代之外的任何其他操作,我将无法对其进行测试。
【问题讨论】:
标签: php unit-testing collections phpunit stub