简体   繁体   中英

Is this integration test or unit test? (testing rest controller in spring)

I write tests for my rest controller in spring. And I have two questions.
1. Is this integration test or unit test?
2. Should I test here validation annotations like @NotNull and @Valid and other? If no, how to disable them? Because when I pass incorrect json to post request these annotations by default will give me bad request error in response.

External dependencies like services are mocked and class has @ExtendWith(SpringExtension.class) @WebMvcTest(value = UserController.class, secure = false) annotations.

@Test
void findByUsername_returnUser() throws Exception {
    when(userService.findByUsername(USERNAME)).thenReturn(Optional.ofNullable(user));
    when(converterContext.getConverter(ConverterShowUserDto.class)).thenReturn(converterShowUserDto);
    when(converterShowUserDto.convert(user)).thenReturn(showUserDto);
    this.mockMvc.perform(get("/user?username=" + USERNAME))
            .andDo(print())
            .andExpect(status()
                    .isOk())
            .andExpect(jsonPath("$.username", is(USERNAME)));
}

My example controller method looks like:

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity getById(@PathVariable(value = "id") @ExistAccountWithId int id) {
    Optional<User> user = userService.findById(id);
    ShowUserDto showUserDto = convert(user.get());
    return new ResponseEntity<>(showUserDto, HttpStatus.OK);
}

Validation is based only on custom annotations and exceptions are caught globally. So I dont have any validation inside controller methods. They are separated from each other.

Is this integration test or unit test?

This is unit test. Here you are testing your controller. But it is slightly more than unit test I would say. Because you are testing not only your controller file(UserController), but the controller layer of spring( @WebMvcTest(...) ).

Should I test here validation annotations like @NotNull and @Valid and other? If no, how to disable them? Because when I pass incorrect json to post request these annotations by default will give me bad request error in response.

Yes you have to(Or rather you can). That is what I meant, here you can test not only the contoller file, but the controller layer. You can disable this if you want by registering a mockvalidator.

External dependencies like services are mocked and class has

hence it is not an integration test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM