Skip to content

Instantly share code, notes, and snippets.

@behrangsa
Created June 23, 2019 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save behrangsa/127a97cd1704c4369c4ac2e217db2224 to your computer and use it in GitHub Desktop.
Save behrangsa/127a97cd1704c4369c4ac2e217db2224 to your computer and use it in GitHub Desktop.
A good test case
@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:

  1. It has no boilerplate code
  2. It is small so it is possible to understand its intention quickly
  3. 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");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment