Валидация при использовании WebMvcTest

@Validated
@Controller
public class AuthController {

    @GetMapping("/activate/{tail}")
//  @Validated
    public String activateAccount(@PathVariable @NotBlank(message = "Path variable must not be blank") 
            @Size(min=8, max=8, message = "Path variable should be 8 chars length") String tail) {
            
                // some logic here
                
    response.setStatus(HttpServletResponse.SC_GONE);
    model.addAttribute("message", "Link has been expired, try to register again");
    return "auth/home";
    }

}

@ControllerAdvice(AuthController.class)
public class ConstraintViolationExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    ModelAndView handleConstraintValidation(ConstraintViolationException exc, 
            HttpServletResponse response) { 

    ModelAndView mav = new ModelAndView("error");
    
    // some logic here
            
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return mav;
    }

}

@WebMvcTest(AuthController.class)
class AuthControllerTest {

    @Test
    void violated_activation() throws Exception {
    
        String tail = "tail";       
        mockMVC.perform(get("/activate/{tail}", tail).with(csrf()))
            .andExpect(status().isBadRequest())
            .andExpect(content().string(containsString("Path variable should be 8 chars length")))
            .andExpect(view().name("error"));
        
        tail = " ";
        mockMVC.perform(get("/activate/{tail}", tail).with(csrf()))
            .andExpect(status().isBadRequest())
            .andExpect(content().string(containsString("Path variable must not be blank")))
            .andExpect(view().name("error"));
        
        tail = "";
        mockMVC.perform(get("/activate/{tail}", tail).with(csrf()))
            .andExpect(status().isNotFound());
        tail = null;
        mockMVC.perform(get("/activate/{tail}", tail).with(csrf()))
            .andExpect(status().isNotFound());
    
    }

}

Почему тест проходит с @Validated на уровне класса контроллера, но не уровне метода контроллера?


Ответы (0 шт):