【发布时间】:2017-01-04 13:44:38
【问题描述】:
我在这个问题上纠结了一段时间,我不确定为什么 PHPunit 看不到这个函数正在被调用。
这是我要测试的代码:
public function handle()
{
$path = $this->request->getPath();
$requestMethod = $this->request->getMethod();
if (!$path) {
$this->redirect('home');
} else if (!$this->isMethodPathFound($path, $requestMethod)) {
$this->redirect('404');
} else {
$handler = $this->getControllerFullName($this->routes[$path]['handler']);
if (is_callable($handler)) {
call_user_func($handler);
} else {
$this->redirect('404');
}
}
}
/**
* @param string $path
* @param int $statusCode
*/
public function redirect($path, $statusCode = 303)
{
if (defined('TESTING_ENVIRONMENT') && TESTING_ENVIRONMENT) {
return;
}
header(
'Location: ' . $this->request->getProtocol() .
$this->request->getHost() . '/' . $path,
true,
$statusCode
);
die();
}
为标头函数设置了 TESTING_ENVIRONMENT 变量,因此它不会在运行 PHPunit 时触发(我不想创建另一个类来拥有该重定向功能,只是为了能够模拟它以进行一次测试),这是测试代码:
public function testHandlePathIsEmpty()
{
$requestMock = $this->getMockBuilder('\services\Request')->getMock();
$requestMock->expects($this->once())->method('getPath')->willReturn('');
$requestMock->expects($this->once())->method('getMethod')->willReturn('GET');
$routerMock = $this->getMockBuilder('\services\Router')
->setConstructorArgs([$this->routes, $requestMock])
->enableProxyingToOriginalMethods()
->getMock();
$routerMock->expects($this->once())->method('redirect')
->with('asdasd')->willReturn(true);
$routerMock->handle();
}
$routerMock 对象绝对应该调用“redirect”函数,并且它说它不会被调用..即使当我在函数内部进行 var_dump/die 时,它确实会进入其中。
感谢您的帮助!
【问题讨论】: