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