0
我使用phpUnit并通过扩展PHPUnit_Extensions_Database_TestCase
来编写涉及数据库的测试。 如何模拟数据库故障以测试我的错误检查?我应该测试什么样的失败发生,除了数据库被关闭?如何在单元测试时模拟db失败
我发现this Ruby on Rails question,但发现它与phpUnit无关。
我使用phpUnit并通过扩展PHPUnit_Extensions_Database_TestCase
来编写涉及数据库的测试。 如何模拟数据库故障以测试我的错误检查?我应该测试什么样的失败发生,除了数据库被关闭?如何在单元测试时模拟db失败
我发现this Ruby on Rails question,但发现它与phpUnit无关。
我把代码块分开,然后use Mocks/Stubs in PHPUnit去控制从数据库调用返回来包含错误,所以我的主代码会处理这个错误。我不使用实际的数据库,而是测试执行交互的代码,以通过例外或您的代码期望的方法来处理数据库错误。
为了模拟从您的代码与模拟相同的回报,你会做以下几点:使用
$stub = $this->getMock('YourDBClass');
// Configure the stub to return an error when the RunQuery method is called
$stub->expects($this->any())
->method('RunQuery')
->will($this->throwException(new SpecificException));
您可以测试的@expectsException
/**
* @expectedException SpecificException
*/
public function testDBError()
{
$stub = $this->getMock('YourDBClass');
// Configure the stub to return an error when the RunQuery method is called
$stub->expects($this->any())
->method('RunQuery')
->will($this->throwException(new SpecificException));
$stub->RunQuery();
}
或使用setExpectedException
public function testDBError()
{
$stub = $this->getMock('YourDBClass');
// Configure the stub to return an error when the RunQuery method is called
$stub->expects($this->any())
->method('RunQuery')
->will($this->throwException(new SpecificException));
$this->setExpectedException('SpecificException');
$stub->RunQuery();
}
然后您将以相同的方式测试已知回报
public function testDBQueryReturns1()
{
$stub = $this->getMock('YourDBClass');
// Configure the stub to return an error when the RunQuery method is called
$stub->expects($this->any())
->method('RunQuery')
->will($this->returnValue(1));
$this->assertEquals(1, $stub->RunQuery(), 'Testing for the proper return value');
}