如何在单元测试时模拟数据库故障


How to simulate db failures when unit testing

我使用 phpUnit 并通过扩展PHPUnit_Extensions_Database_TestCase来编写涉及数据库的测试。如何模拟数据库故障以测试错误检查?除了数据库关闭之外,我应该测试哪些类型的故障?

我发现了Ruby on Rails的问题,但发现它与phpUnit无关。

我将代码块分开,然后在 PHPUnit 中使用 Mocks/Stubs 来控制从数据库调用返回以包含错误,因此我的主代码将处理错误。 我不使用实际的数据库,而是测试执行交互的代码,以通过异常或代码期望的任何方法处理数据库错误。

若要使用模拟模拟代码的相同返回,请执行以下操作:

$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();  
}

或使用 setExpectException

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');
}