I want to create JUnit5 tests for Rest 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");
}
Full code: Github
But when I run the test I get exception
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
Rest service code: GitHub
I tried to add @NoArgsConstructor but I get warning that variables (UsersService userService, PasswordAdminResetHandler resetHandler and etc...) are not initialized.
Do you know how I can fix this issue?
Please do these two steps to resolve the issues
@Mock
annotation instead of @Spy
annotation
OR@Autowired
annotation from constructor as it's automatically injected. Read this for more information ...