Home > Software design >  Mock instance of a private controller in another class during tests
Mock instance of a private controller in another class during tests

Time:10-26

I have a controller that makes a request to an API (ExampleController).

public class ExampleController {
     public String getDownloadURL(String a, String b, String c){
          // performs GET request
          return response;
     }
}

This controller is used as part of a function in another class (ExampleMemberClass).

 public class ExampleMemberClass() {
     private ExampleController controller = new ExampleController();

     public String getMemberDownloadURL(Object o, String c) {
        // some logic
        // generate variable b
        String responseURL = controller.getDownloadURL(a, b, c);
        // some logic
        return responseURL;
     }
 }

I want to create a Unit Test for ExampleMemberClass where I test the logic of getMemberDownloadURL, without running the actual getDownloadURL request. (I want to mock a response using Mockito/PowerMock instead)

CodePudding user response:

One way you could do this is to add a couple of constructors to ExampleMemberClass, one with no arguments and one that takes a ExampleController as an arg. e.g.

private ExampleController controller;

public ExampleMemberClass() {
 controller = new ExampleController();
}

public ExampleMemberClass(ExampleController controller) {
 this.controller = controller;
}

In your ExampleMemberClass unit test you can use the second constructor to pass a mocked ExampleController that returns whatever responseURL you want.

  • Related