我正在尝试创建一个模拟控制器,但我不断收到捕获参数的错误。它说想要但没有调用。我仍然对 Mockito 和 Junit 以及它应该如何正常工作感到困惑。
控制器模拟
@Test
public void testAddUserController() throws Exception {
JSONArray userArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "User 1");
jsonObject.put("email", "user1@email.com");
jsonObject.put("password", "password123");
jsonObject.put("address", "Address 1");
jsonObject.put("age", 12);
userArray.put(jsonObject);
mockMvc.perform(MockMvcRequestBuilders.post(BASE_URL + "/users").content(toString()).contentType(MediaType.APPLICATION_JSON_UTF8));
Mockito.verify(userService, Mockito.times(1))
.addUser(userCaptor.capture(), emailCaptor.capture(), passwordCaptor.capture(), addressCaptor.capture(), ageCaptor.capture());
Assert.assertEquals("User 1", userCaptor.getValue());
Assert.assertEquals("user1@email.com", emailCaptor.getValue());
Assert.assertEquals("password123", passwordCaptor.getValue());
Assert.assertEquals("Address 1", addressCaptor.getValue());
Assert.assertEquals("12", ageCaptor.getValue());
}
用户服务
boolean addUser(String username, String email, String password, String address, Integer age);
UserServiceImpl
@Override
public boolean addUser(String username, String email, String password, String address, Integer age) {
Optional<User> user = userRepository.findByUsernameAndEmail(username, email);
if (!user.isPresent()) {
User user1 = new User();
user1.setUsername(username);
user1.setEmail(email);
user1.setPassword(password);
user1.setAddress(address);
user1.setAge(age);
user1.setIsActive(true);
userRepository.save(user1);
return true;
} else {
return false;
}
}
通过
@Test
编写一个junit测试,并使用Mockito
来模拟HttpResponse
InputStream jsonResponse = createJsonResponse();
Mockito.when(mHttpClientMock.execute(Mockito.isA(HttpPost.class))).thenReturn(mHttpResponseMock);
Mockito.when(mHttpResponseMock.getStatusLine()).thenReturn(mStatusLineMock);
Mockito.when(mStatusLineMock.getStatusCode()).thenReturn(HttpStatus.SC_OK);
Mockito.when(mHttpResponseMock.getEntity()).thenReturn(mHttpEntityMock);
Mockito.when(mHttpEntityMock.getContent()).thenReturn(jsonResponse);
参考: https://dzone.com/articles/how-test-rest-api-junit