gpt4 book ai didi

spring-mvc - 注释 Controller 的 Junit 测试

转载 作者:行者123 更新时间:2023-12-05 04:18:52 24 4
gpt4 key购买 nike

我如何在我的 Controller 中测试以下方法

@RequestMapping(method = RequestMethod.POST)
public String register(@Valid User user, BindingResult result) {

if (result.hasErrors()) {
return "users/registration";
}

// create user
service.create(user);

return "redirect:/";
}

如何测试 @Valid 和 BindingResult?

public void testRegister() {
try {
request.setMethod("POST");
request.setRequestURI("/users");
request.setParameter("email", "bla@gmail.com");
request.setParameter("prename", "Cyril");
request.setParameter("surname", "bla");
request.setParameter("password", "123");
request.setParameter("repeat", "123");
request.setParameter("birthdate", "2000-01-01");
request.setParameter("city", "Baden");


ModelAndView mAv = adapter.handle(request, response, usersController);

assertEquals("redirect:/", mAv.getViewName());
} catch (Exception e) {
fail();
}
}

非常感谢

最佳答案

对于 @Valid 注释,这超出了单元测试的范围。您可以相信 Spring 框架会为您执行验证,适本地设置 BindingResult

实际上,您只需要覆盖 result.hasErrors()if 检查 - 为此,您应该模拟 BindingResult;这是使用 Mockito 的方法:

...
@Mock
private BindingResult mockBindingResult

@Before
public void setupTest() {
MockitoAnnotations.initMocks(this);
// While the default boolean return value for a mock is 'false',
// it's good to be explicit anyway:
Mockito.when(mockBindingResult.hasErrors()).thenReturn(false);
}

@Test
public void shouldStayOnRegistrationPageIfBindingErrors() {
// Simulate having errors just for this test:
Mockito.when(mockBindingResult.hasErrors()).thenReturn(true);

ModelAndView mav = controller.register(user, mockBindingResult);

// Check that we returned back to the original form:
assertEquals("users/registration", mav.getViewName());
}

我也发现使用 Cobertura 真的很好(尤其是 eCobertura Eclipse 插件)以直观地确认单元测试涵盖了每一行和分支。

关于spring-mvc - 注释 Controller 的 Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8299607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com