2013-10-02 48 views

回答

2

我把代码块分开,然后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'); 
}