1

I am using Slim 2 and PHPUnit, and want to test that making a GET request to a specific endpoint results in a redirect. I have tried getting the headers of the response, but they show a 200 since the response is the correctly-loaded page to which I am redirected.

Here is how redirects work in the app. Basically, if the Slim Auth middleware throws an Unauthorised Exception, it redirects to the login page:

$app->error(function (\Exception $e) use ($app) {
    if ($e instanceof HttpUnauthorizedException) {
        return $app->redirectTo('/login');
    }
});
GluePear
  • 7,244
  • 20
  • 67
  • 120

1 Answers1

0

If the piece of code you provided is all you want to test, I think you necessarily don't need to check the actual response object. It would be enough to write a test to verify that the error handling function you wrote calls redirectTo('/login') from $app object when and instance of HttpUnauthorizedException is given to it as input argument. The error handling function is the only unit that you wrote in this code snippet, the other parts (like error and redirectTo methods from $app object) are only called in your code and you don't need to write any tests for them, that's why I suggest not checking the actual response object because in that case somehow you're tightly coupling test code for error handling function to the redirectTo method from Slim framework and that would not be a unit test anymore.

So I suggest you not to write the error handling function as an anonymous function, so you can write unit tests for that particular function. Then you can write tests for it and use a library like Mockery to provide a mocked $app object to this function and with Mockeyr's help (old methods like shouldRecieve or the newer allows method) you can make sure that redirectTo('/login') is being called on that mocked object if an instance of HttpUnauthorizedException is passed to it.

Also, this question seems relevant Slim Framework endpoint unit testing

Nima
  • 3,309
  • 6
  • 27
  • 44