I am trying to test a function that talks to an API. This method should be able to handle errors thrown by the HTTP client (like API throttling etc.) and act appropriately (for example by waiting a bit and then sending the request again.
I am trying to test this with PHPSpec, but it seems that it doesn't pick up on the fact that I want to have two different results from the same method call (the first one should throw an Exception telling my client to wait, while the second one should return the actual data). Does anyone know of a way to handle this?
Here's an example of a method on my class that respects a 400 error sent by the API, which I would like to test:
You should mock the http instance and when calling postJson make it return a correct response for the first test and throw an exception for the second test.
I dont remember exactly the code but something like this
But does this work in PHPSpec? Because when I have both calls, it just passes, even though I have no handler in place for the exception thrown. Does the order of the calls to the mock matter?
I dont know with php spec. But I guess you have to have a test for each situation, like every testing library. One for moking the dependancy and to make it return correct value, one to make it throw an exception.
The thing is, when the HTTP client throws an error, I want to be able to call the same method again with the exact same arguments and get a different result (no exception thrown, but actual results returned).
I can't test the exception path without also returning real data from the method afterwards. That's the problem as I see it.