Spring MVC:如何从返回String的控制器方法单元测试Model的属性?

use*_*379 3 java junit spring unit-testing spring-mvc

例如,

package com.spring.app;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(final Model model) {
        model.addAttribute("msg", "SUCCESS");
        return "hello";
    }

}
Run Code Online (Sandbox Code Playgroud)

我想使用JUnit 来测试model其属性及其值home().我可以改变返回类型以ModelAndView使其成为可能,但我想使用String它因为它更简单.但这不是必须的.

无论如何都要检查model而不改变home()返回类型?或者它无法帮助?

Ser*_*man 7

你可以使用Spring MVC Test:

mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(model().attribute("msg", equalTo("SUCCESS"))) //or your condition
Run Code Online (Sandbox Code Playgroud)

在这里充分说明例子


use*_*379 7

我尝试使用副作用来回答这个问题。

@Test
public void testHome() throws Exception {
    final Model model = new ExtendedModelMap();
    assertThat(controller.home(model), is("hello"));
    assertThat((String) model.asMap().get("msg"), is("SUCCESS"));
}
Run Code Online (Sandbox Code Playgroud)

但我对此仍然不是很有信心。如果这个答案有一些缺陷,请留下一些评论来改进/贬低这个答案。