org.mockito.exceptions.base.MockitoException: Please ensure that the type 'UserRestService' has a no-arg constructor

Viewed 7652

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?

3 Answers

Another option is to create the Spy userRestService explicitly

@Spy
private UserRestService userRestService = new UserRestService(...);

and use created Spys or Mocks(as needed) as arguments

Please do these two steps to resolve the issues

  1. Try to use @Mock annotation instead of @Spy annotation OR
  2. Remove @Autowired annotation from constructor as it's automatically injected. Read this for more information ...

You have two options:

1) Remove final declaration from fields so that the default constructor becomes available for Mockito to use.

2) Provide a no-args Constructor (simply a constructor that does not take any parameters) and initialize the fields in question yourself.

Related