This is what I done in my project:
Somewhere in your project configuration:
@LoadBalanced
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
RestTemplate restTemplate = builder.build();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
return restTemplate;
}
@Bean
public SomeRestClass someRestClass () {
SomeRestClass someRestClass = new SomeRestClass (environment.getProperty("someservice.uri"), restTemplate(new RestTemplateBuilder()));
return parameterRest;
}
And SomeRestClass:
public class SomeRestClass {
private final RestTemplate restTemplate;
private final String someServiceUri;
public LocationRest(String someServiceUri, RestTemplate restTemplate) {
this.someServiceUri= someServiceUri;
this.restTemplate = restTemplate;
}
public String getSomeServiceUri() {
return locationUri;
}
public SomeObject getSomeObjectViaRest() {
//making rest service call
}
}
And Test class for SomeRestClass
:
@RunWith(SpringRunner.class)
@RestClientTest(SomeRestClass.class)
public class SomeRestClassTest {
@Autowired
private SomeRestClass someRestClass;
@Autowired
private MockRestServiceServer server;
@Test
public void getSomeObjectViaRestTest() throws JsonProcessingException {
SomeResponseObject resObject = new SomeResponseObject();
ObjectMapper objectMapper = new ObjectMapper();
String responseString = objectMapper.writeValueAsString(resObject);
server.expect(requestTo(locationRest.getSomeServiceUri() + "/some-end-point?someParam=someParam")).andExpect(method(HttpMethod.POST))
.andRespond(withStatus(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON_UTF8).body(responseString));
someRestClass.getSomeObjectViaRest();
}
}
Note: I diasbled eureka client because otherwise you have to mock a eureka server. So I added eureka.client.enabled=false in test application.properties