I have a Rest Service Client which I am trying to test.
This is the client method I’m trying to test:
public RestPriceRow getPriceRow(String customer, String product, String qt)
throws Exception {
// Prepare acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_XML);
// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<PriceRowDto> entity = new HttpEntity<PriceRowDto>(headers);
// Prepare response
RestPriceRow res = new RestPriceRow();
// Send the request as GET
try {
ResponseEntity<PriceRowDto> result =
restTemplate.exchange(baseURL + "{customerId}/{productId}/{quantity}",
HttpMethod.GET, entity, PriceRowDto.class, customer,product,qt);
PriceRowDto response = result.getBody();
return response;
} catch (Exception e) {
e.printStackTrace();
}
}
And this is my test class:
@Before
public void setUp() {
RestTemplate r = mock(RestTemplate.class);
restPriceService = new RestPriceServiceImpl();
restPriceService.setRestTemplate(r);
restPriceService.setBaseURL("url");
}
@Test
public void prueba() {
PriceRowDto r = new PriceRowDto("100","200","9","10","0","19/11/2012");
try {
when(restPriceService.getPriceRow("100","200","16")).thenReturn(r);
} catch (Exception e) {
e.printStackTrace();
}
}
My problem is that when I run this test, it throws me a NullPointerException when executing result.getBody(). (result is null)
You mixed up the SUT (System Under Test) with the mocked Collaborators. The SUT is the thing who’s method you test. The Collaborators play along and return data as needed for the SUT to work.
RestPriceServicethat you want to testsut: TODOrestTemplate: OKrestTemplateMock: TODOsut: OKwhen(restTemplateMock.exchange(...).thenReturn(r): TODOsut.getPriceRow: TODORestPriceRowreturned by this call is correct: TODOrestTemplateMock: TODOEdit:
If you want to read a very good book about the different forms of unit tests, I can recommend XUnit Test Patterns.