...

/

Mocking Out Dependencies

Mocking Out Dependencies

Dependencies often make testing hard. Our code needs to get the status of airports from a remote web service. The response from the service will be different at different times due to the nature of the data. The web service may fail intermittently, the program may run into a network failure, and so on. All these situations make it hard to write unit tests, which should be FAIR, for a piece of code that has to talk to such non-deterministic, and by their nature, unreliable external dependencies. This is where mocks come in.

A mock is an object that stands in for the real object, much like how a stunt person, instead of your favorite high-paid actor, stands in or jumps off a cliff in an action thriller. During normal execution the code under test will use the real dependency. During automated testing, however, the mock will replace the real dependency so the test can be run FAIRly.

Using mock

To facilitate unit testing of code with dependencies, the test will prepare a mock to return a canned response, attach the mock to the code under test, run the test, verify the result is as expected, and, finally, verify with the mock that the code under test interacted with its dependency as expected.

To learn how to create and use mocks, let’s turn our attention to the method that will get data from the remote FAA web service. Given an airport code, the web service returns a JSON response with the airport status data. Getting this data involves two actions: first, we have to send a request to the service URL and, second, we have to parse the response and deal with any possible errors.

Parsing data is straightforward; given a string containing JSON data, extract the necessary details from it. If there was an error, deal with it appropriately. We can easily write tests for that. It’s getting the data from the URL that makes this feature unpredictable and hard to test. We can mock that part out by using a level of indirection.

We can devise the solution ...