如何在单元测试时模拟db故障

时间:2013-10-02 01:11:46

标签: php database unit-testing phpunit

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

我找到了this Ruby on Rails question,但发现它与phpUnit无关。

1 个答案:

答案 0 :(得分:2)

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

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

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