Kevin
Kevin

Reputation: 6292

How do people write unit test in this scenario

I have a question regarding unit test.

I am going to test a module which is an adapter to a web service. The purpose of the test is not test the web service but the adapter.

One function call the service provide is like:

class MyAdapterClass {

  WebService webservice;

  MyAdapterClass(WebService webservice) {
    this.webservice = webservice;
  }

  void myBusinessLogic() {
    List<VeryComplicatedClass> result = webservice.getResult();
    // <business logic here>
  }
}

If I want to unit test the myBusinessLogic function, the normal way is to inject an mocked version of webservice with getResult() function setup for some predefined return value.

But here my question is, the real webservice will return a list of very completed classes each with tens of properties and the list could contain hundreds or even thousands of element.

If I am going to manually setup a result using Mockito or something like that, it is a huge amount of work.

What do people normally do in this scenario? What I simply do is connect to the real web service and test again the real service. Is something good to do?

Many thanks.

Upvotes: 1

Views: 158

Answers (2)

davidfrancis
davidfrancis

Reputation: 3849

One thought I had reading the comments would be to introduce a new interface which can wrap List<VeryComplicatedClass> and make myBusinessLogic use that instead.

Then it is easy (/easier) to stub or mock an implementation of your new interface rather than deal with a very complicated class that you have little control over.

Upvotes: 2

mikej
mikej

Reputation: 66313

You could write the code to call the real web service and then serialize the List<VeryComplicatedClass> to a file on disk and then in the setup for your mock deserialize it and have mockwebservice.getResult() return that object. That will save you manually constructing the object hierarchy.

Update: this is basically the approach which Gilbert has suggested in his comment as well.


But really.. you don't want to set up a list of very completed classes each with tens of properties and the list could contain hundreds or even thousands of element, you want to setup a mock or a stub that captures the minimum necessary to write assertions around your business logic. That way the test better communicates the details that it actually cares about. More specifically, if the business logic calls 2 or 3 methods on VeryComplicatedClass then you want the test to be explicit that those are the conditions that are required for the things that the test asserts.

Upvotes: 4

Related Questions