2014-02-14 87 views
0

我目前正在为我编写的mysqli包装类编写单元测试。PHPUnit对于相同的代码具有不同的行为

其中一项测试是使用错误的凭证检查连接到MySQL。

这是类c'tor代码:

public function __construct($host, $userName, $password, $databaseName) 
{ 
    $this->m_sqlConn = new mysqli($host, $userName, $password, $databaseName); 
    if(!mysqli_connect_error()) 
    { 
      //... 
    } 
    else 
    { 
     throw new FailedToConnectDatabaseException($this->getLastDatabaseErrorStr()); 
    } 
} 

当调试我的PHP代码(与XDebug的),没有错误,也没有异常的时候抛出创建新的mysqli

(我运行这个行:)

$conn = new MySQLConnection("localhost", "WRONG_USERNAME", "WRONG_PASSWORD", "NON_EXISTANT_DB"); 

但是当PHPUnit的运行相同的代码时,测试:

public function test_wrongCredentials() { 
     $this->object = new MySQLConnection("localhost", "WRONG_USERNAME", "WRONG_PASSWORD", "NON_EXISTANT_DB"); 
    } 

到达错误处理程序说

“的mysqli :: mysqli的()(HY000/1045):拒绝访问用户 'WRONG_USERNAME' @ 'localhost' 的(使用密码:YES)”

可能是什么原因,或者有什么我不知道的?

+0

你想要我们随机猜测,还是要提出一些代码? –

+0

@DamienBlack增加了类,php单元,调试代码。 – Taru

+0

我们需要你PHPunit的代码,因为这是抛出错误。 –

回答

0

你得到的异常预计是因为你的代码具体抛出它。

在PHPUnit中处理这个问题的方法是使用annotation来告诉它'预期异常'。在你的情况下,适当的注释很奇怪,@expectedException

所以你的测试应该是这个样子: -

/** 
* @expectedException FailedToConnectDatabaseException 
*/ 
public function test_wrongCredentials() 
{ 
    $this->object = new MySQLConnection("localhost", "WRONG_USERNAME", "WRONG_PASSWORD", "NON_EXISTANT_DB"); 
} 

这应该使你的测试通过,而不诉诸使用邪恶@。

相关问题