2

我正在向正在生产中的现有 Spring 2.5 代码库添加自动化测试。我正在尝试在我的控制器中测试 onSubmit() 方法。

这是控制器视图的 XML 配置:

<property name="formView" value="createPublicBroadcastsForm" />
<property name="successView" value="redirect:createBroadcastsResults.htm" />

这是我的 JUnit 测试:

@Before
public void setup() {
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
}

@Test
public void displayForm() throws Exception {
    ModelAndView mv = controller.handleRequest(request, response);
    assertViewName(mv, controller.getFormView());
    }

@Test
public void testSubmitCreate() throws Exception {

    request.setMethod("POST");
    request.addParameter("title", "qwerty");
    request.addParameter("startDate", "02/22/2013 09:00 AM");
    request.addParameter("hours", "1");
    request.addParameter("minutes", "1");
    request.addParameter("seconds", "1");
    request.addParameter("repeats", "None");

    ModelAndView mv;
    try {
        mv = controller.handleRequest(request, response);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    assertViewName(mv, controller.getSuccessView());
}

displayForm() 中的断言通过,但 testSubmitCreate() 中的断言失败,因为 ModelAndView 中的视图名称是“createPublicBroadcastsForm”,而不是预期的“redirect:createBroadcastsResults.htm”

我看过的几件事是 controller.handleRequest() 没有抛出异常,甚至没有调用控制器的 onSubmit() 方法,并且我在调用 super 后重写了 isFormSubmission() 以打印值.isFormSubmission(),它返回 true。

此外,如果我将测试更改为直接调用控制器的 onSubmit() 而不是 handleRequest(),则测试通过:

PublicBroadcastCommand command = new PublicBroadcastCommand();
command.setTitle("qwerty");
command.setStartDate(DateUtils.createDate(2013, 2, 22, 9));
command.setHours(1);
command.setMinutes(1);
command.setSeconds(1);
command.setRepeats("None");
ModelAndView mv = controller.onSubmit(request, response, command, null);
assertViewName(mv, controller.getSuccessView());

所以我想知道我是否应该通过调用 handleRequest() 或 onSubmit() (或两者,其中 onSubmit() 是一个单元测试,而 handleRequest() 更像是一个集成测试)来测试控制器?关于尝试通过调用handleRequest()进行测试的问题有什么想法吗?

4

0 回答 0