如何使用RedirectAttributes测试Spring MVC控制器

时间:2012-06-30 11:26:04

标签: spring-mvc junit

我正在使用:

  • Spring 3.1
  • JUnit 4.10

我正在尝试使用RedirectAttributes为控制器编写一个junit测试用例。

Controller的签名是:

@RequestMapping(method = RequestMethod.POST)
public String homePOST(@Validated({ IBasic.class }) @ModelAttribute("userCommand") User userCommand,
            BindingResult result, Model model,
            RedirectAttributes flashAttributes)

JUnit测试用例是:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "/root-context.xml", "/servlet-context.xml" })
public class HomeControllerTest {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Test
    public void testHomePOST() {
        MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
        request.addParameter("username", "user1");
        request.addParameter("password", "mypasswd");

        MockHttpServletResponse response = new MockHttpServletResponse();

        Object handler;

        try {
            handler = handlerMapping.getHandler(request).getHandler();

            ModelAndView modelAndView = handlerAdapter.handle(request,
                    response, handler);

            assertViewName(modelAndView, "redirect:/myview");
        } catch (Exception e) {
            String err = "Error executing controller : " + e.toString();

            fail(err);
        }
    }
}

执行handlerAdapter.handle()时,我得到:

java.lang.AssertionError: Error executing controller : java.lang.NullPointerException
at org.junit.Assert.fail(Assert.java:93)
at com.myapps.service.impl.test.HomeControllerTest.testHomePOST(HomeControllerTest.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

如果我从控制器中删除RedirectAttributes,它可以正常工作。

任何人都可以提供一些如何使用RedirectAttributes测试控制器的帮助吗?

提前谢谢。

为了模拟这个,这里是控制器代码:

@Controller
@RequestMapping(value = "/")
public class HomeController {
    @RequestMapping(method = RequestMethod.POST)
    public String homePOST(
            @Validated({ IBasic.class }) @ModelAttribute("userCommand") User userCommand,
            BindingResult result, Model model,
            RedirectAttributes flashAttributes) {

        return "redirect:/myview";
    }
}

2 个答案:

答案 0 :(得分:5)

我能够复制你的问题 - 问题的根本原因是如果RedirectAttributes作为处理程序方法参数出现,那么在从处理程序适配器返回之前,将拉出输出“flashmap”并添加flashAttributes它。现在,从httprequest中检索此输出flashMap - 在您的情况下,对于MockHttpServletRequest,这是null。

修复是在MockHttpServletRequest中简单设置虚拟输出flashMap:

request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE,new FlashMap());

这对我有用。你可以试着看看它是否为你解决了这个问题。

答案 1 :(得分:0)

使用mockito框架来模拟它。 使用

RedirectAttributes flashAttributes;
flashAttributes=Mockito.mock(RedirectAttributes.class)

在设置功能中。