考虑一个存储用户信息的简单类:
<?php
class UserStore {
private $users = array();
function addUser($name, $mail, $pass) {
if (isset($this->users['mail'])) {
throw new Exception("User {$mail} already in system.\n");
}
if (strlen($pass) < 5) {
throw new Exception("Password must have 5 or more letters.");
}
$this->users[$mail] =
array(
'pass' => $pass,
'mail' => $mail,
'name' => $name,
);
return true;
}
function notifyPasswordFailure($mail) {
if(isset($this->users[$mail])) {
$this->users[$mail]['failed'] = time();
}
}
function getUser($mail) {
return $this->users[$mail];
}
}
这是我们的测试用例,以确保课程不会出现重复的电子邮件ID:
<?php
class UserStoreTest extends PHPUnit_Framework_TestCase {
private $store;
public function setUp() {
$this->store = new UserStore();
}
public function tearDown() {
}
public function testAddUserDuplicate() {
try {
$ret = $this->store->addUser("Bob", "a@b.com", "123456");
$ret = $this->store->addUser("Bill", "a@b.com", "123456");
self::fail('Exception should\'ve been thrown.');
} catch (Exception $e) {
$const = $this->logicalAnd(
$this->logicalNot($this->contains("Bill")),
$this->isType('array')
);
self::AssertThat($this->store->getUser("a@b.com"), $const);
}
}
}
这个例子来自一本书。逻辑似乎很简单:一旦在添加重复用户时抛出异常,我们确保getUser()
不会给第二个用户。所以我运行此测试并得到以下错误:
有1次失败:
1) UserStoreTest::testAddUserDuplicate
Failed asserting that Array (
'pass' => '123456'
'mail' => 'a@b.com'
'name' => 'Bill'
) does not contain 'Bill' and is of type "array".
WTF?测试失败了!怎么样?查看测试输出,我看到一个名为Bill的数组。这怎么可能?我看到它的方式,Bill从未添加到用户,因为抛出异常,那么为什么我们在输出中看到它?我在理解PHPUnit /这个例子时犯了错误,或者这本书的例子是错误的。请帮忙!
答案 0 :(得分:4)
您的addUser
方法中存在拼写错误 - 应该是
if (isset($this->users[$mail])) {
throw new Exception("User {$mail} already in system.\n");
}
顺便说一句,我认为这是一个糟糕的测试,因为你甚至无法从第一个视图中得到错误:)