我在Symfony2上下文中遇到了PHPUnit问题。我正在测试以下方法:
public function updatePassword(LdapUserInterface $user)
{
$data = array();
Attribute::setPassword($data, $user->getPassword(), Attribute::PASSWORD_UNICODEPWD);
try {
$this->ldap->bind();
$this->ldap->update($user->getDn(), $data);
return true;
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
throw new ConnectorException($this, 'Connector cannot connect to directory.');
} finally {
$this->ldap->disconnect();
}
return false;
}
我使用 finally 指令PHP> 5.5。我的单一测试是($ this-> logger引用 setUp 方法中定义的存根):
/**
* @expectedException UserBundle\Connectors\Exceptions\ConnectorException
*/
public function testUpdatePasswordException()
{
$ldap = $this->getMockBuilder(Ldap::class)
->disableOriginalConstructor()
->setMethods(array('bind', 'disconnect', 'update'))
->getMock();
$ldap->method('update')->will($this->throwException(new LdapException($ldap, 'Fake Exception')));
$user = $this->getMockBuilder(User::class)
->setMethods(array('getDn', 'getPassword'))
->getMock();
$user->expects($this->once())->method('getPassword')->willReturn('#!12345mD');
$user->expects($this->once())->method('getDn')->willReturn('cn=John Doe,ou=people,dc=athome.com,dc=com');
$connector = new LdapConnector($this->logger, $ldap);
$connector->updatePassword($user);
}
UT没有触发任何异常并且失败了。显然,问题来自 finally 指令。通常, disconnect 方法被调用一次,这就是我将其添加到存根中的原因。但是,当我删除它时,测试通过。 在调试时,调用所有指令(try,catch,finally,然后触发异常)。我不明白这些行为,这是一个php问题吗?似乎没有,所以我想知道我的模拟或 phpunit 是否存在问题。
有什么想法吗?