我正在尝试测试一个简单的Laravel模型,该模型需要“密码”和“电子邮件”属性。我的测试内容如下......
public function testEmailIsRequired() {
$user = new User;
$user->password = 'derp';
// should not save
$this->assertFalse($user->save());
}
而不是正确地同意“这不起作用”和成功的测试,我得到......
1) UserTest::testEmailIsRequired
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation:
19 NOT NULL constraint failed: users.email
(SQL: insert into "users" ("password", "updated_at", "created_at")
values (derp, 2014-09-26 15:27:07, 2014-09-26 15:27:07))
[...]
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
我担心我在这里完全是新手。在我看来,PHPUnit应该是压制数据库驱动程序自己的错误报告,只是接受“假”......帮助?
答案 0 :(得分:0)
您的测试正在寻找返回false的函数。由于您正在调用函数,因此函数中生成的任何其他错误仍将被返回。
public function testEmailIsRequired()
{
$user = new User;
$user->password = 'derp';
// should not save
$this->assertFalse($user->save());
}
public function testMockSaveWorks()
{
$Mock = $this->getMock('User', array('save'));
// Set up the expectation for the getResult() method
$Mock->expects($this->any())
->method('save')
->will($this->returnValue(true));
$this->assertTrue($Mock->save());
}
class User()
{
...
public function save()
{
if( is_null($this->email) )
return false;
...
return true;
}
}
然后你应该使用Mocks来删除实际的save()函数及其与数据库的关系,并让mock返回true以假装保存记录以显示你已经测试了模块。