简体   繁体   中英

Mockito doesn't work with custom validator in Spring

I am using Mockito to test one of my get-mappings in the controller class. Here is my get method

 @PostMapping(value = "insert/carbooking")
    public ResponseEntity<Void> reservation(@Valid BookingRequest bookRequest) {
        return validate(bookRequest, carService::booking);
    }

At the top of my class is my Validator

  @Autowired
  private ReservationValidator reservationValidator;

  @InitBinder("bookRequest")
    protected void bookRequestBinder(WebDataBinder binder) {
        binder.addValidators(reservationValidator);
    }

Here is the Mockito test method. The result should have returned bad request since the sin is in wrong format.

@Test
    public void reservationTest2() throws Exception {

        mockMvc.perform(MockMvcRequestBuilders
                .post("insert/carbooking")
                .param("license", "data")
                .param("SIN", "202007191517")
                .accept(MediaType.MULTIPART_FORM_DATA))
                .andExpect(status().isBadRequest());
    }

But the test fail

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

Is there any way for the Mockito to receive the "reservationValidator" ?

I got everything fixed thanks to @chrylis-onstrike- . For the source code, I just need to remove @Before addholders set up method and replace it with the annotation @Autowired on Mockmvc mockmvc and @MockBean on service class which put the client class on the application context. It's such a shame I could not give tick mark to his answer since he didn't post the answer to my question rather commenting on it.

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