0
我正在使用PDO和PHPUnit進行專業項目。如何測試PDO :: execute()失敗
這裏是方法,在我的代碼庫,我想測試:
public function signUp(\PDO $pdo)
{
$statement = $pdo->prepare("INSERT INTO user VALUES (
DEFAULT,
:firstName,
:lastName,
:salutation,
:birthday,
:email,
:password
)");
$statement->bindValue(':firstName', $this->firstName);
$statement->bindValue(':lastName', $this->lastName);
// Etc...
if($statement->execute()) {
$this->id = $pdo->lastInsertId();
return $this->id;
}
return 0;
}
我想找到我的$statement->execute()
失敗的方式,並根據PDO documentation
並且測試返回false
方法,我想實現:
testSignupInsertRowFailAndReturnZeroValue()
這樣做有道理嗎?
EDIT
下面是一個簡單的模擬的解決方案:
$pdoMock = $this->getMockBuilder('PDO')
->disableOriginalConstructor()
->getMock();
$pdoMock->method("prepare")
->will($this->returnValue(new \PDOStatement()));
使用的try/catch異常處理的可能? – Maximus2012 2015-03-31 19:31:55
[模擬你的PDO對象](http://erichogue.ca/2013/02/best-practices/mocking-pdo-in-phpunit/)返回一個模擬語句對象? – 2015-03-31 19:32:06
是的,謝謝你的好主意。我將用我的實現編輯我的問題。你是這個意思嗎 ? – 2015-03-31 20:06:35