0

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

我发现了这个 Ruby on Rails question,但发现它与 phpUnit 无关。

4

1 回答 1

4

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

要使用 mock 从您的代码中模拟相同的返回,您可以执行以下操作:

$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');
}
于 2013-10-02T15:17:11.523 回答