MockMVC return 200 instead of 400

55 views Asked by At

Writing Spring app with rest-architecture. I have controller that receive DTO and return response entity. Also i have validation for DTO and spring security (basic authentification).

So when i'm testing it with Postman it works as espected - it returns 400 when i sent not valid DTO, otherwise 200. In negative test case (not valid DTO) - test method return always 200.

@PostMapping("/create")
    @PreAuthorize("hasAnyAuthority('ADMIN', 'MANAGER')")
    public ResponseEntity<?> createAccount(@RequestBody @Valid AccountCreationRequestDto accountDTO,
                                           BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseEntity.status(400).body(bindingResult.getAllErrors());
        }
        AccountDto account = accountService.createAccount(accountDTO);
        return ResponseEntity.status(200).body(account);
    }
------------------------
public class AccountCreationRequestDto{

    @NotBlank(message = "Client ID cannot be blank") private String clientId;
    @NotBlank(message = "Account Type cannot be blank") private String accountType;
    @NotBlank(message = "Currency Code cannot be blank") private String currencyCode;

}
------------------------
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@SpringBootTest(classes = BankAppApplication.class, properties = {"spring.profiles.active=test"})
class AccountControllerTest {

@Autowired
    MockMvc mockMvc;

    @MockBean
    AccountServiceImpl accountService;

    @Autowired
    AccountController accountController;
@Test
    void createAccountTestNotValidRequest() throws Exception {
        AccountCreationRequestDto accountCreationRequestDto = new AccountCreationRequestDto();
        accountCreationRequestDto.setClientId("");
        accountCreationRequestDto.setAccountType("");
        accountCreationRequestDto.setCurrencyCode("");

        mockMvc.perform(post("/account/create")
                        .with(user("admin").authorities(new SimpleGrantedAuthority("ADMIN")))
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(new ObjectMapper().writeValueAsString(accountCreationRequestDto)))
                .andExpect(status().isBadRequest());
    }

I expect status 400 because controller receive not valid DTO. But i got:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /account/create
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"50"]
             Body = {"clientId":"","accountType":"","currencyCode":""}
    Session Attrs = {SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=admin, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ADMIN]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ADMIN]]]}

Handler:
             Type = com.example.bankapp.controller.AccountController
           Method = com.example.bankapp.controller.AccountController#createAccount(AccountCreationRequestDto, BindingResult)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"0", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status expected:<400> but was:<200>
Expected :400
Actual   :200
0

There are 0 answers