The integration test that we wrote for the REST API earlier will start failing because of invalid credentials.
Let's update the integration test to supply the 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);
}
};
}
createHeaders creates a Base64-encoded basic authentication header. HttpHeaders headers = createHeaders("user-name", "user-password") sets up the headers variable with a basic authentication header.
We would need to send this header when executing the REST API request. The following code shows the updated test:
@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);
}
We are using template.exchange to send the headers—new HttpEntity<String>(null, headers).
Similar changes need to be performed on all other integration test methods in BasicControllerIT and TodoControllerIT.