2015-03-31 53 views
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())); 
+0

使用的try/catch异常处理的可能? – Maximus2012 2015-03-31 19:31:55

+1

[模拟你的PDO对象](http://erichogue.ca/2013/02/best-practices/mocking-pdo-in-phpunit/)返回一个模拟语句对象? – 2015-03-31 19:32:06

+0

是的,谢谢你的好主意。我将用我的实现编辑我的问题。你是这个意思吗 ? – 2015-03-31 20:06:35

回答

0

execute返回true上的成功和false失败具体根据Docs

如果我正确理解你的问题,你可以检查您的查询的东西,如失败:

if($statement->execute()) { 
    // success 
} 
else{ 
    // failure 
} 
+0

是的,但我的问题不是关于实现。这是关于写一个测试,触发一个不成功的案例,并断言这是一个失败。 – 2015-03-31 20:10:04