Integration testing

The integration test we wrote for the service earlier will start failing because of invalid credentials. We will now update the integration test to supply basic authentication credentials:

    private TestRestTemplate template = new TestRestTemplate();
HttpHeaders headers = createHeaders("user-name", "user-password");

HttpHeaders createHeaders(String username, String password) {
return new HttpHeaders() {
{
String auth = username + ":" + password;
byte[] encodedAuth = Base64.getEncoder().encode
(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);
set("Authorization", authHeader);
}
};
}

@Test
public void retrieveTodos() throws Exception {
String expected = "["
+ "{id:1,user:Jack,desc:"Learn Spring MVC",done:false}" + ","
+ "{id:2,user:Jack,desc:"Learn Struts",done:false}" + "]";
ResponseEntity<String> response = template.exchange(
createUrl("/users/Jack/todos"), HttpMethod.GET,
new HttpEntity<String>(null, headers),
String.class);
JSONAssert.assertEquals(expected, response.getBody(), false);
}

Some important things to note are as follows:

  • createHeaders("user-name", "user-password"): This method creates Base64. getEncoder().encode basic authentication headers
  • ResponseEntity<String> response = template.exchange(createUrl("/users/Jack/todos"), ;HttpMethod.GET,new HttpEntity<String>(null, headers), String.class): The key change is the use of HttpEntity to supply the headers that we created earlier to the REST template
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset