我想为 Rest API 创建 JUnit5 测试。
@Test
public void resetRequest_NAME_AND_EMAIL_MISMATCH() throws Exception {
when(userRestService.resetRequest(anyString(), anyString())).thenReturn(Boolean.valueOf("test"));
MvcResult result = mockMvc.perform(post("/users/reset_request")
.contentType(MediaType.APPLICATION_JSON)
.content(ResetUserDTO))
.andExpect(status().isBadRequest())
.andReturn();
assertEquals(result.getResponse().getContentAsString(), "NAME_AND_EMAIL_MISMATCH");
}
完整代码:Github
但是当我运行测试时出现异常
org.mockito.exceptions.base.MockitoException: Unable to initialize @Spy annotated field 'userRestService'.
Please ensure that the type 'UserRestService' has a no-arg constructor.
.....
Caused by: org.mockito.exceptions.base.MockitoException: Please ensure that the type 'UserRestService' has a no-arg constructor.
... 68 more
休息服务代码:GitHub
我尝试添加 @NoArgsConstructor 但我收到警告,变量(UsersService userService、PasswordAdminResetHandler resetHandler 等)未初始化。
你知道我该如何解决这个问题吗?
最佳答案
另一种选择是显式创建 Spy userRestService
@Spy
private UserRestService userRestService = new UserRestService(...);
并使用创建的 Spys 或 Mocks(根据需要)作为参数
关于java - org.mockito.exceptions.base.MockitoException : Please ensure that the type 'UserRestService' has a no-arg constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62448186/