我有一个我正在嘲笑的方法被报告为被调用0次,即使它似乎确定应该被调用1次。
这是我的测试类方法(简化):
function testFailedPasswordLogin() {
$badPassword = 'NOT'.$this->testPassword;
// setup a fake user repo that returns our test user (since we're passing valid username, just incorrect password)
$this->Users = $this->getMock('Users', array('getByUsername'));
$this->Users->method('getByUsername')->with($this->testUser->username)->willReturn(null);
$this->Auth = new Auth($this->Users);
$this->assertFalse($this->Auth->login($this->testUser->username,$badPassword));
$loggedInUser = $this->Auth->user();
$this->assertEquals(null, $loggedInUser);
}
更新:我甚至决定尝试使用另一个模拟框架(Prophecy):
$this->Users = $this->prophesize('Users');
$this->Users->getByUsername($this->testUser->username)->shouldBeCalled();
$this->Auth = new Auth($this->Users->reveal());
我得到完全相同的失败。
正在测试我的类(也简化为只有方法和构造函数):
class Auth {
public function __construct(Users $Users) {
$this->Users = $Users;
$this->sessionKey = 'Auth.user';
}
public function login($username, $password) {
$user = $this->Users->getByUsername($username);
if ($user && ($user->password == $this->Users->hashPassword($password))) {
$_SESSION[$this->sessionKey] = $user;
return true;
}
else return false;
}
/** Get currently logged-in user **/
public function user() {
if (empty($_SESSION[$this->sessionKey])) return null;
else return $_SESSION[$this->sessionKey];
}
}
运行时,我收到此错误(稍加编辑以在此处正确显示):
有1次失败:
1)AuthTest :: testFailedPasswordLogin 方法名称的期望失败等于string:getByUsername when 调用1次。 预计方法被调用1次,实际上被称为0次。
FAILURES! 测试:5,断言:16,失败:1。
我正准备拔掉这头发。我承认我刚开始使用模拟但是我不能为我的生活找出为什么我的模拟方法没有被调用。
我查看了PHPUnit mocked method called 0 times while it should be called once和PHPUnit - Symfony2 : Method was expected to be called 1 times, actually called 0 times,似乎都没有解决我的具体问题。
我正在运行PHP 5.3.10和PHPUnit 4.7.3。
任何人都可以提供的任何帮助都将非常感谢我保持理智。任何可能有用的其他信息,请告诉我。我将继续研究自己,但到目前为止,我认为没有理由不应该根据文档进行研究。