2016-08-01 81 views
2

我想在Spring Boot 1.4中执行单元测试来测试我的验证返回无效查询字符串参数400。Spring Boot 1.4单元测试休眠验证WebMvcTest

控制器

@RestController 
@Validated 
public class ExampleController { 

    ... 

    @RequestMapping(value = "/example", method = GET) 
    public Response getExample(
      @RequestParam(value = "userId", required = true) @Valid @Pattern(regexp = MY_REGEX) String segmentsRequest { 

     // Stuff here 
    } 

} 

异常处理程序

@ControllerAdvice 
@Component 
public class GlobalExceptionHandler { 

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); 

    // 400 - Bad Request 
    @ExceptionHandler(value = {ConstraintViolationException.class}) 
    @ResponseStatus(HttpStatus.BAD_REQUEST) 
    public void constrainViolationHandle(HttpServletRequest request, ConstraintViolationException exception) { 
     logger.error("Error Bad Request (400)"); 
    } 

} 

语境

@Bean 
public Validator validator() { 
    final ValidatorFactory validatorFactory = Validation.byDefaultProvider() 
      .configure() 
      .parameterNameProvider(new ReflectionParameterNameProvider()) 
      .buildValidatorFactory(); 
    return validatorFactory.getValidator(); 
} 

@Bean 
public MethodValidationPostProcessor methodValidationPostProcessor() { 
    final MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor(); 
    methodValidationPostProcessor.setValidator(validator()); 
    return methodValidationPostProcessor; 
} 

单元测试

@RunWith(SpringRunner.class) 
@WebMvcTest(ExampleController.class) 
public class ExampleControllerTest { 

    private static final String EMPTY = ""; 

    @Autowired 
    private MockMvc mvc; 

    @Test 
    public void test() throws Exception { 

     // Perform Request 
     ResultActions response = this.mvc.perform(
      get("/example").param("userId", "invalid") 
     ); 

     // Assert Result 
     response.andExpect(status().isBadRequest()) 
       .andExpect(content().string(EMPTY)); 
    } 

} 

然而,当我跑我的测试,我收到了200不是400。当我作为应用程序运行而不是作为测试时,验证不会执行。

我认为这可能是由于它在执行测试时没有拿起两个验证bean? 此验证工作

回答

1

@WebMvcTest您使用的注释是在所谓的独立MockMvc配置之上的Spring Boot包装。这MockMvc功能测试独立控制器没有任何其他豆。

为了能够测试更广泛的网络配置,您需要使用web application setup

@RunWith(SpringRunner.class) 
@WebAppConfiguration 
@ContextConfiguration("my-servlet-context.xml") 
public class MyWebTests { 

    @Autowired 
    private WebApplicationContext wac; 

    private MockMvc mockMvc; 

    @Before 
    public void setup() { 
     this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); 
    } 

    // ... 

} 

但是请注意,这样的Web应用程序安装不拿起所有的豆类。例如,您需要显式注册Servler过滤器或Spring Security。但我认为应包括验证。

+0

我试过这个,但后来我得到404s – ptimson