Junit测试带注释的控制器

时间:2011-11-28 17:13:46

标签: spring-mvc junit

如何在我的控制器中测试以下方法

@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();
        }
    }
很多

1 个答案:

答案 0 :(得分:1)

对于@Valid注释,这超出了单元测试的范围。您可以相信Spring Framework将为您执行验证,并正确设置BindingResult

实际上,您只需要覆盖if result.hasErrors()的{​​{1}}检查 - 为此,您应该嘲笑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插件)来直观地确认每个行和分支都被单元测试覆盖是非常好的。