Mocking Test Methodology

The key idea of mocking is to replace real code (e.g. calls to a database or service) with artificial functionality that has the same return type. There are different approaches in this practice. Here, I explain best practices and why it might be better to avoid mocking in order to have real code quality.

User Service - Example to Be Tested With Mocks

Let’s write simple application that fetch users from http service.

Java

public Optional<User> createUser(String name) {
        try {
            //Preparation of request: auth, body and media type of request
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(APPLICATION_JSON);
            headers.set("auth", "mySecretKey");
            //Specifying body
            HttpEntity<String> request =
              new HttpEntity<String>("{\"name\":" + name + "}", headers)
            //Making request with and deserializing response into User object
            User newUser = (new RestTemplate()).postForEntity("/server/users",                                                      request, User.class).getBody();
            newUser.setIssueDate(Date.now());
            return Optional.of(newUser);
        } catch (Exception e) {
            System.out.println("Something went wrong! : " + e.getMessage());
            Return Optional.empty();
        }
}
@Data
class User {
    private Integer id;
    private String name;
    private Date issueDate;
}

Implementation Details

The method, createUser, basically does 4 things:

  1. Preparation of request: authentication, preparing body and media type of request (line 4-5 corresponding to 1, 2, 3 step on the diagram.
  2. Making request to server with given url (line 11 or step 4).
  3. Receiving the response and deserializing it into an object. (line 11- yes the same line! and step 9 on diagram).
  4. Setting the current date to created user (line 12, or step 10).

The remaining actions are done on server-side and hidden from application:

1. Server check that body has json type and correct auth key (step 5,6).

2. Make business logic (create a user) (step 7).

3. Generate response with new user id (step 8).

createUser workflow

#performance #testing #spring #mockito #powermock #mock #http server #http testing

Use Mocks in Testing? Choose the Lesser Evil!
1.35 GEEK