org.mockito.exceptions.base.MockitoException:请确保类型 'UserRestService' 具有无参数构造函数
org.mockito.exceptions.base.MockitoException: Please ensure that the type 'UserRestService' has a no-arg constructor
我想为 Rest 创建 JUnit5 测试 API。
@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 等)未初始化。
你知道我该如何解决这个问题吗?
你有两个选择:
1) 从字段中删除最终声明,以便默认构造函数可供 Mockito 使用。
2) 提供一个无参数构造函数(只是一个不带任何参数的构造函数)并自行初始化相关字段。
请执行以下两个步骤来解决问题
- 尝试使用
@Mock
注释而不是 @Spy
注释
或者
- 从构造函数中删除
@Autowired
注解,因为它是自动注入的。 Read this for more information ...
另一种选择是显式创建 Spy userRestService
@Spy
private UserRestService userRestService = new UserRestService(...);
并使用创建的 Spys 或 Mock(根据需要)作为参数
我想为 Rest 创建 JUnit5 测试 API。
@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 等)未初始化。
你知道我该如何解决这个问题吗?
你有两个选择:
1) 从字段中删除最终声明,以便默认构造函数可供 Mockito 使用。
2) 提供一个无参数构造函数(只是一个不带任何参数的构造函数)并自行初始化相关字段。
请执行以下两个步骤来解决问题
- 尝试使用
@Mock
注释而不是@Spy
注释 或者 - 从构造函数中删除
@Autowired
注解,因为它是自动注入的。 Read this for more information ...
另一种选择是显式创建 Spy userRestService
@Spy
private UserRestService userRestService = new UserRestService(...);
并使用创建的 Spys 或 Mock(根据需要)作为参数