2011-09-05 42 views
1

如何使我的存根行为像一个ArrayIterator,例如?我的意思是,我想遍历这个存根。这是来自实践PHP测试的练习。PHPUnit - 存根类似于构建类型

7.2 
Write a EvenIterator which takes a FibonacciIterator an iterates only 
on the even-indexed values (returning 0, 1, 3, 8, 21...). 
7.3 
Write tests for the EvenIterator class, stubbing out the 
FibonacciIterator using an ArrayIterator in substitution, which is provided 
by the Spl (otherwise it will never terminate!) 

谢谢。

+0

对FibonacciIterator的正常调用看起来像什么? – Fenton

+0

它实现了一个迭代器。你可以调用$ a = new FibonacciIterator(7)。之后,您可以迭代0,1,1,2,3,5,8。谢谢。 – thom

+0

这个任务不是说'使用ArrayIterator作为FibonacciIterator的存根'吗? – Mchl

回答

3

如果我理解正确,这里的任务是使用ArrayIterator作为FibonacciIterator的存根测试EvenIterator。 因此,例如加载ArrayIterator与偶数值数组,传递给EvenIterator,你应该得到相同的值。然后对奇数值数组执行相同操作,并且应该获得空的结果集。


class EvenIteratorTest extends \PHPUnit_Framework_TestCase { 

    public function testDoesNotRemoveEvens() { 

    $data = array(2,4,6,8); 
    $arrayIterator = new \ArrayIterator($data); 
    $object = new EvenIterator($arrayIterator); 

    $expected = $data; 
    $actual = array(); 
    foreach($object as $v) { 
     $actual[] = $v; 
    } 
    $this->assertEquals($expected,$actual); 
    } 

    public function testFiltersOutOdds() { 

    $data = array(1,3,5,7); 
    $arrayIterator = new \ArrayIterator($data); 
    $object = new EvenIterator($arrayIterator); 

    $actual = array(); 
    foreach($object as $v) { 
     $actual[] = $v; 
    } 
    $this->assertEmpty($actual); 
    } 

} 

正如你可以看到,有很多重复的代码,所以一些重构将到位。

+0

你可以用代码来解释你说的吗?非常感谢Mchl。 – thom

+0

SUre。它非常简单(结果有点难看),因为我不知道你的实现细节,或者你使用的是哪个测试框架。 – Mchl

+0

哦,是啊...只是注意到它是PHPUnit ...傻我... – Mchl