@Test
public void showProject_shouldReturnAccessDenied_forUnauthenticatedUser() {
// Given an unauthenticated get project request
HttpEntity request = unauthenticatedRequest("GET /projects/1");
// When the request is handled by the application
ResponseEntity<ErrorResponse> response = handleRequest(request);
// Then a forbidden response should be returned
assertThat(response).hasStatus(FORBIDDEN)
.isJson()
.hasMessage("Access Denied");
}
Now I call this a good JUnit test case:
- It has no boilerplate code
- It is small so it is possible to understand its intention quickly
- It tests what it is supposed to test
It will become more concise if we declare variables using the var
keyword:
@Test
public void showProject_shouldReturnAccessDenied_forUnauthenticatedUser() {
// Given an unauthenticated get project request
var request = unauthenticatedRequest("GET /projects/1");
// When the request is handled by the application
var response = handleRequest(request);
// Then a forbidden response should be returned
assertThat(response).hasStatus(FORBIDDEN)
.isJson()
.hasMessage("Access Denied");
}
And even more concise if we combine unauthenticatedRequest
/handleRequest
:
@Test
public void showProject_shouldReturnAccessDenied_forUnauthenticatedUser() {
// Given an unauthenticated get project request
var response = handleUnauthenticatedRequest("GET /projects/1");
// Then a forbidden response should be returned
assertThat(response).hasStatus(FORBIDDEN)
.isJson()
.hasMessage("Access Denied");
}