junit测试错误地通过了错误的参数

zynd9foi  于 2021-07-22  发布在  Java
关注(0)|答案(1)|浏览(397)

我试着测试一个控制器的方法并得到正确的异常。它仅对constraintviolationexception(javax.validation)失败,而对其他测试(如missingservletrequestparameterexception或methodargumenttypemismatchexception)失败,测试按预期工作。
下面是我的代码的一部分,在控制器(@validated)中,在方法中添加这些注解。还有控制器建议和测试。postman,当我输入错误的参数时,返回正确的响应:{“value”:500,“name”:“constraintviolationexception”,“message”:“the param1 is wrong”},但是由于某种奇怪的原因,junit要求200而不是500。
控制器

@ResponseBody
    public Board method(@Min(value = 0) @Max(value = 5)  @RequestParam(value = "param1", required = true) int param1,
                     @Min(value = 0) @Max(value = 1)  @RequestParam(value = "param2", required = true) int param3){
        return service.meth(param1, param2);
    }

控制器建议

@ExceptionHandler(value = ConstraintViolationException.class)
    public ErrorResponse handleInternalServerErrors(HttpServletRequest request, Exception ex) {
        String message = "";
        if(ex instanceof ConstraintViolationException) {
            Map<String, Collection<String>> errors = new LinkedHashMap<>();
            final String[] queryParam = {""};
            ((ConstraintViolationException) ex).getConstraintViolations().forEach(constraintViolation -> {
                String queryParamPath = constraintViolation.getPropertyPath().toString();
                queryParam[0] = queryParamPath.contains(".") ?
                        queryParamPath.substring(queryParamPath.indexOf(".") + 1) :
                        queryParamPath;
            });
            message = "The " + queryParam[0] + " is wrong";
        }

        return new ErrorResponse(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                ex.getClass().getSimpleName(),
                message);
    }

测试

@Test
    void TryToGetException() throws Exception {
        given(service.meth(1231,1231)).willReturn(new CustObj());
        MockHttpServletResponse response = mvc.perform(get("/endpoint")
                .param("param1", "1231")
                .param("param2", "1231")

        ).andReturn().getResponse();

        assertEquals(response.getStatus(), HttpStatus.INTERNAL_SERVER_ERROR.value());
    }

预期:200实际:500
为了在测试中获得异常,我应该更改什么?
提前谢谢!

ctrmrzij

ctrmrzij1#

private MockMvc mvcContext;
@Autowired
private WebApplicationContext context;
@BeforeEach
public void setUp() {
    mvcContext = MockMvcBuilders
            .webAppContextSetup(context)
            .build();
}

通过使用 webAppContextSetup ,问题解决了。它考虑了@min,@max(在我的例子中,genarally是@valid注解),所以我可以有一个例外来测试它!

@Test
void testConstraintViolationException() throws Exception {
   MockHttpServletResponse response = mvcContext.perform(get("/endpoint")
            .param("param1", "1231")
            .param("param2", "1231")
    assertEquals(response.getStatus(), HttpStatus.INTERNAL_SERVER_ERROR.value());
}

相关问题