Unit Testing – How to Unit Test a Class Requiring Web Service Call

integration-teststddunit testingweb services

I'm trying to test a class which calls some Hadoop web services. The code is pretty much of the form:

method() {
    ...use Jersey client to create WebResource...
    ...make request...
    ...do something with response...
}

e.g. there is a create directory method, a create folder method etc.

Given that the code is dealing with an external web service that I don't have control over, how can I unit test this? I could try and mock the web service client/responses but that breaks the guideline I've seen a lot recently: "Don't mock objects you don't own". I could set up a dummy web service implementation – would that still constitute a "unit test" or would it then be an integration test? Is it just not possible to unit test at this low a level – how would a TDD practitioner go about this?

Best Answer

In my opinion you should mock the webservice calls if this is a unit test, as opposed to an integration test.

Your unit test should not test whether the external webservice is working, or whether your integration with it is correct. Without getting too dogmatic about TDD, note that a side effect of turning your unit test into an integration test is that it's likely to run slower, and you want fast unit tests.

Also, if the webservice is temporarily down or working incorrectly, should this cause your unit test to fail? It doesn't seem right. Your unit test should fail for only one reason: if there is a bug in the code in that "unit".

The only portion of code that is relevant here is ...do something with response.... Mock the rest.