Home > front end >  How to mock an dependency when passed as an argument?
How to mock an dependency when passed as an argument?

Time:05-20

We created a common class where a RestTemplate is passed as a parameter. This rest template is used to facilitate:

  • postForEntity
  • exchange

However, since it is not Autowired in the common class, I am not able to create unit tests that mocks the RestTemplate. Is there a work around for this?

Setup:

Spring boot Project A - initiates a rest integration and utilises the common class. This Project A instantiates the @Autowired RestTemplate rest template and pass it as a parameter to the common class method.

Spring boot Common Class - conducts the rest integration but uses the rest template passed by Project A. This common class I am unable to conduct the unit test since I cannot mock the Rest Template.

This is a java spring boot project.

Addendum:

**COMMON CLASS

public class RestService {


     public static void invoke(RestTemplate restTemplate, RequestDetails requestDetails) {

      switch (requestDetails.getHttpMethod()) {
            case POST:
                HttpEntity<?> postEntity = new HttpEntity<>(request, httpHeaders);
                restResponse = restTemplate.postForEntity(requestDetails.getUrl(), postEntity, String.class);
                break;
            case GET:
                HttpEntity<?> getEntity = new HttpEntity<>(httpHeaders);
                restResponse = restTemplate.exchange(requestDetails.getUrl(),
                    HttpMethod.GET, getEntity, String.class);
                break;
            default:
                break;

        }

    }

}

** INVOKING CLASS

public class InvokingClass {

    @Autowired
    private RestTemplate restTemplate;


     public void invoke() {

     //RequestDetails construct here ...

        RestService.invoke(restTemplate,requestDetails)
    }

}

CodePudding user response:

I'm not sure what you are trying to achieve. If you want to test your RestService you should be able to do something like this:

    @Test
    void test() {
        RestTemplate templateMock = mock(RestTemplate.class);
        RestService.invoke(templateMock, new RequestDetails());
        verify(templateMock).postForEntity(any(URI.class), any(Object.class), any(Class.class));
    }

If this is not what you're looking for please provide more details on what you're trying to test. Thanks.

  • Related