所以我正在搞乱symfony路由器组件,我创建了一个小包装器。
有一件事是我如何获得投掷500单位测试的请求?问题的方法是:
public function processRoutes(Request $request) {
try {
$request->attributes->add($this->_matcher->match($request->getPathInfo()));
return call_user_func_array($request->attributes->get('callback'), array($request));
} catch (ResourceNotFoundException $e) {
return new RedirectResponse('/404', 302);
} catch (Exception $e) {
return new RedirectResponse('/500', 302);
}
}
有问题的测试是:
public function testFiveHundred() {
$router = new Router();
$router->get('/foo/{bar}', 'foo', function($request){
return 'hello ' . $request->attributes->get('bar');
});
$response = $router->processRoutes(Request::create('/foo/bar', 'GET'));
$this->assertEquals(500, $response->getStatusCode());
}
现在测试将失败,因为我们已经定义,状态代码将是200.我可以对我创建的Request对象做些什么特别的事情,让它抛出500?
答案 0 :(得分:1)
我认为你可以在这里找到几个选项:
public function processRoutes(Request $request) {
...
if ($request->getRequestUri() == '/path/that/throws/exception') {
throw Exception('Forced to throw exception by URL');
}
...
}
public function testFiveHundred() {
...
$response = $router->processRoutes(Request::create('/path/that/throws/exception', 'GET'));
...
}
DummyRequest
对象,该对象将扩展您的原始Request类,并确保此对象将引发异常(例如 - 您确定使用getPathInfo()
,因此您可以使用此)。
class DummyRequest extends Request {
public function getPathInfo() {
throw new Exception('This dummy request object should only throw an exception so we can test our routes for problems');
}
}
public function testFiveHundred() {
...
$dummyRequest = new DummyRequest();
$response = $router->processRoutes($dummyRequest);
...
}
由于我们getRequestUri
的函数$dummyRequest
会引发异常,因此您对$router->processRoutes
的调用会让我们的假人抛出异常。
这是一个普遍的想法,你可能需要在那里使用命名空间和函数(我没有测试它,但这应该有用)。