How to test a BadRequest exception on a POST request

Viewed 200

I made a test that checked whether a post method from my controller does what it's supposed to. It worked great! Now I'm supposed to make a test to see whether the right message pops up when I get an 400 error for that post method.

Here's what I've got:

public void shouldReturnBadRequestExceptionWhenGivenBadArguments() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(user);

    mvc.perform(post("/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content(json))
            .andExpect(status().isBadRequest())
            .andExpect(result -> assertEquals("Email is already taken!", Objects.requireNonNull(result.getResolvedException()).getMessage()))
//            .andExpect(result -> assertTrue(result.getResolvedException() instanceof BadRequestException));
}

The test gives me an error as such: Status expected:<400> but was:<200>. Now I do understand that it just means I didn't get an error and instead the post method worked. Now the thing I don't know how to do is to get that error on purpose. Anyone know how to do this?

EDIT: was told to post the controller endpoint so here it is:

@PostMapping
public UserDTO addUser(@RequestBody CreateUserDTO newUser) {
    log.info(newUser.toString());
    return userService.createUser(newUser);
}

and my user was created in my setUp() (with @BeforeEach annotation) as such:

@BeforeEach
public void setUp() throws Exception {
    user = new User(
            "ime",
            "prezime",
            "imeprezime@consulteer.com",
            "1234");
}

Hope this helps!

EDIT 2: added a part of service class concerning the post method:

@Override
public UserDTO createUser(CreateUserDTO newUser) {
        if(userRepository.findByEmail(newUser.getEmail()).isPresent())
            throw new BadRequestException("Email is already taken!");

        return userMapper.convertEntityToDTO(userRepository.save(userMapper.convertCreateDTOToEntity(newUser)));

}
0 Answers
Related