'How to mock an dependency when passed as an argument?
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)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
