Gabriel Pulga
Gabriel Pulga

Reputation: 293

How do i mock the behavior of a void method when unit testing my delete service?

I'm currently unit testing the endpoints of a Spring Boot CRUD RESTful API and i have the following "Delete user by its id" endpoint that's composed of a controller and a service to implement its logic :

Delete controller (it's mainly calling the logic of the service and defining some guidelines) :

 @RestController
    @RequestMapping("/users/{id}")
    public class DeleteUserController {

        @Autowired
        DeleteUserService service;

        @DeleteMapping
        @ResponseStatus(HttpStatus.NO_CONTENT)
        public void deleteUser_whenDeleteUser(@PathVariable Long id) {
            service.deleteUser(id);
        }
    }

Delete service :

@Service
public class DeleteUserService {

    @Autowired
    UserRepository repository;

    public void deleteUser(Long id) {

        repository.findById(id)
                .orElseThrow(() -> new UserNotFoundException(id));

        repository.deleteById(id);
    }
}

While everything seems to be working fine until now, i'd be grateful if someone could tell me what i could improve in the code above. Anyways, My controllers unit test is the problem i can't seem to solve :

@RunWith(SpringRunner.class)
@WebMvcTest(DeleteUserService.class)
public class DeleteUserControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private DeleteUserService deleteUserService;

    @Test
    public void removeUserById_whenDeleteMethod() throws Exception {
        User user = new User();
        user.setName("Test Name");
        user.setId(89L);

        doNothing().when(deleteUserService).deleteUser(user.getId());

        mvc.perform(delete("/users/" + user.getId().toString())
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isNoContent());
    }

I'm getting a java.lang.AssertionError: Status because while the code is expecting to get a 204 No content response status, it's receiving a 404 Not found which means it's throwing the exception that's supposed to throw when the user doesn't exist.

I think the answer is in the way i need to mock the behavior of my services logic, but i have no idea how. Would appreciate if someone could help me with this one.

Upvotes: 1

Views: 1567

Answers (1)

Michiel
Michiel

Reputation: 3410

The WebMVC test layer is not configured to include the controller under test; DeleteUserController. The 404 refers to the missing requestmapping instead of a functional user not found. Use @WebMvcTest(DeleteUserController.class) instead of @WebMvcTest(DeleteUserService.class).

Upvotes: 1

Related Questions