Testing for Error Cases
Get an overview of error case testing and unit testing for adapters in detail.
We'll cover the following
Error case testing
The application design allows multiple ways to simulate errors for testing purposes:
-
We can make an API call to the actual service that results in an error and then capture the result using VCR. We can use this approach in an integration or adapter test.
-
We can stub a method that’s internal to the adapter. For example, we can stub the
client
method to return a double that simulates an API error. We’d use this in an adapter test. -
We can stub the adapter to return an unexpected value in a client test.
Which approach we choose depends on the details of the library we’re working with. Often, stubbing the external service makes sense for the same reason that stubbing ActiveRecord methods does. Crafting a call that will reliably return an error is not always possible. If we can, try to stub methods of our adapter rather than methods of the third-party gem. It’s generally a good idea to stub only the code we control.
Adapters unit testing
Keeping tests consistent with the location of the logic being tested is still a good policy. Use adapter tests to ensure that the adapter behaves gracefully when it gets weird responses from the server. (Normally, server or gem exceptions shouldn’t leak out of the adapter). Use unit tests to ensure that the clients can handle whatever the adapter does in response to unexpected input.
Note: Test the error code based on which object in the system needs to respond to the error.
Get hands-on with 1400+ tech skills courses.