Spring Boot does not throw HttpMessageNotReadableException

256 views Asked by At

There is a simple loginController with loginRequest annotated with @RequestBody

@RestController
public class LoginController{
    @PostMapping("/login")
    public ResponseEntity<?> doLogin(@Valid @RequestBody LoginRequest loginRequest, BindingResult bindingResult){
    }
}
// ...

public class LoginRequest {

    @NotBlank(message = "Email/Phone Can not be empty")
    private String emailAddressOrPhoneNumber;

    @NotBlank(message = "Password Can not be empty")
    private String password;

    public LoginRequest() {
    }
    // getters and setters
}

I am testing this code via WebMvcTest like this one:

@WebMvcTest(controllers = LoginController.class)
public class LoginControllerMvcTest {
    @Test
    public void test(){
        NewCustomerRequest invalidRequestType = // assume that there is a valid new customer object.
        MvcResult mvcResultForInvalidRequestType = mockMvc.perform("/login")
                .content(objectMapper.writeValueAsString(invalidRequestType))
                .contentType("application/json"))
                .andReturn();
    }
}
// ...
public class NewCustomerRequest {
    @NotBlank(message = "Email can not be empty")
    @EmailValueValidation
    private String emailAddress;

    @PhoneNumberRegexValidation
    private String phoneNumber;

    @NotBlank(message = "Password can not be empty")
    @InvalidPasswordCharacterValidation
    private String password;

    @NotBlank(message = "Password verify can not be empty")
    @InvalidPasswordCharacterValidation
    private String passwordVerify;

What I would like to see is that spring throws the HttpMessageNotReadableException because i am trying to make Login request with different json type.

However, request comes to the controller with these values:

loginRequest.emailAddressOrPhoneNumber = null
loginRequest.passsword = "passwordFromNewCustomerRequest"

How do I force the Spring throws the Exception in that case?

0

There are 0 answers