Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing REST API

I have some experience with unit testing and mocks. In my limited experience I would use the two to test a service layer, for example, mocking (stubbing?) out the database to eliminate dependencies and concentrate on unit testing the business logic.

Now I'm creating a wrapper API implementation that will consume RESTful web services. The json result structure sent back to me is out of my hands, for example: Twitter. I'm simply building the client to interface with their api. I'm unsure how to go about unit testing the json result. Right now I'm just mocking the result of the http request with a static json structure. This ensures that the deserialzing of json to my pojos is correct, but I'm concerned about API changes. What if the api structure changes? What if the api currently returns "title" today and "groovy_title" tomorrow? My unit test wouldn't catch that.

From my understanding though - unit tests are supposed to be quick. Previously I would mock the db and now I'm mocking http, but should I actually be using the concrete http implementation so I'm notified immediately of a breaking api change? Or is there a better way to approach this situation?

like image 477
Mike Avatar asked Feb 25 '12 02:02

Mike


1 Answers

I would continue to do what you are doing and mock the interface between your code and the external API. As you point out, this will not detect changes in the external API.

You could write integration tests that actually go to the external server to test for API changes. I suspect you have separated out the code that does the interaction into its own server/module, so you can literally ping the external API without being obstructed by more than 1 abstraction layer in your app.

Note, you could build these tests without using your app code; i.e. just wget or curl and do some analysis on the results...

The issues with this are numerious; off the top of my head:

You need a network connection
Slower
The external service could be down temporarily -- i.e. failure could mean different things.
etc.

like image 196
hvgotcodes Avatar answered Oct 08 '22 19:10

hvgotcodes