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.
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;
}
The method, createUser
, basically does 4 things:
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).
#performance #testing #spring #mockito #powermock #mock #http server #http testing