2013-10-02 70 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'); 
}