如何到达异常块

时间:2016-08-14 23:55:51

标签: php routing request phpunit symfony

所以我正在搞乱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?

1 个答案:

答案 0 :(得分:1)

我认为你可以在这里找到几个选项:

  1. 确定特定路径始终会抛出异常 这将迫使您对代码进行一些更改。

  2. 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'));
        ...
    }
    
    1. 创建一个DummyRequest对象,该对象将扩展您的原始Request类,并确保此对象将引发异常(例如 - 您确定使用getPathInfo(),因此您可以使用此)。

    2. 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的调用会让我们的假人抛出异常。

        

      这是一个普遍的想法,你可能需要在那里使用命名空间和函数(我没有测试它,但这应该有用)。