【问题标题】:How to simulate db failures when unit testing单元测试时如何模拟数据库故障
【发布时间】:2013-10-08 08:08:17
【问题描述】:

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

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

【问题讨论】:

    标签: php database unit-testing phpunit


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多