Todo API integration testing setup

The code to perform integration testing in the TodoController class is shown in the following code snippet. It launches the entire Spring context, with all the beans defined. This test is very similar to the integration test for BasicController:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TodoControllerIT {
@Autowired
private TestRestTemplate template;

Since the Todo REST API is secured using basic authentication, we would need to supply basic auth credentials to do the integration test.

The code that would be used to create the auth headers is as follows:

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);
}
};
}

Please note the following:

  • createHeaders("user-name", "user-password"): This method creates Base64—encoded headers.
  • ResponseEntity<String> response = template.exchange("/users/Jack/todos", ;HttpMethod.GET,new HttpEntity<String>(null, headers), String.class): The key change here is the use of HttpEntity to supply the headers 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