最后面单元测试运行的一个问题
IteratorTest.php
//...
foreach ($bookList as $book) {
$books[] = $book->getAuthorAndTitle();
}
$this->assertEquals(
[
'Learning PHP Design Patterns by William Sanders',
'Professional Php Design Patterns by Aaron Saray',
'Clean Code by Robert C. Martin',
],
$books
);
这里运行单元测试得到的是
1) DesignPatterns\Behavioral\Iterator\IteratorTest::testCanIterateOverBookList
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 0 => 'Learning PHP Design Patterns ...anders'
- 1 => 'Professional Php Design Patte... Saray'
- 2 => 'Clean Code by Robert C. Martin'
foreach
是遍历 $bookList
的私有变量 $books
,应该提供一个方法获取这个私有变量吧?
class BookList implements \Countable, \Iterator
{
//...
public function getBooks(): array
{
return $this->books;
}
}
然后单元测试的代码应该是
foreach ($bookList->getBooks() as $book) {
$books[] = $book->getAuthorAndTitle();
}