我上过这门课
<?php
class Password
{
protected function checkPassword()
{
$this->callExit();
}
protected function callExit()
{
exit;
}
}
这是我的测试:
public function testAuthorizeExitsWhenPasswordNotSet()
{
$badCode = $this->getMockBuilder(Password::class)
->setMethods(array('callExit'))
->getMock();
$badCode->expects($this->once())
->method('callExit');
$badCode->checkPassword();
}
在前面的类中,callExit
方法是Password类。我的问题是,我可以测试不属于Password
类的方法吗?
例如在checkPassword
方法中:
protected function checkPassword()
{
$user = new User;
$this->callExit();
$user->fillOut();
}
我想为fillOut
方法做一个模拟,我该怎么做?
帮帮我!!
发布于 2017-05-22 21:34:23
按照您的代码编写方式,您不能模拟fillOut
方法,因为您正在实例化要测试的方法中的User
对象。没有办法将对象替换为这样的mock。
为了测试这个方法,您应该向checkPassword
方法传入一个User
对象。然后,您将能够使用模拟的fillOut
方法创建一个MockUser
。
因此,您的方法将如下所示:
protected function checkPassword(User $user) {
$this->callExit();
$user->fillOut();
}
也叫
在您发布的代码中,您正在调用exit()。请记住,如果执行此命令,也会停止PHPUnit。
你还试图显式地测试一个受保护的方法,你真的不应该这样做。您应该只测试类的公共方法。在测试公共方法时,应该执行受保护的方法和私有方法。这使您可以重构类的内部结构,并知道您没有更改类的功能。
如果您觉得需要显式地测试一个受保护的函数,这是一个信号,表明您应该将该方法移动到一个单独的类中,该类将提供给您正在测试的对象。
https://stackoverflow.com/questions/44079046
复制相似问题