Empty content in spring mvc test

Deadly 提交于 2021-02-08 13:20:24

问题


I could not test page content with spring mvc test because it is empty.

Given simplest possible controller:

@RequestMapping(value = "/home")
public String home(HttpSession session, ModelMap model) {
  return "home";
}

relevant tiles config:

<definition name="base.definition" template="/jsp/view/application.jsp">
  <put-attribute name="header" value="/jsp/view/header.jsp" />
  <put-attribute name="menu" value="/jsp/view/menu.jsp" />
  <put-attribute name="title" value="" />
  <put-attribute name="body" value="" />
  <put-attribute name="footer" value="/jsp/view/footer.jsp" />
</definition>
<definition name="home" extends="base.definition">
  <put-attribute name="title" value="Welcome" />
  <put-attribute name="body" value="/jsp/view/home/list-home.jsp" />
</definition>

Simple list-home.jsp

<p>Welcome</p>

And the test:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration()
@ContextConfiguration(classes = WebTestConfig.class)
public class HomeControllerTest {
  @Autowired
  private WebApplicationContext wac;
  private MockMvc mockMvc;

  @Before
  public void _setup() {
    this.mockMvc =   MockMvcBuilders.webAppContextSetup(this.wac).build();
  }

  @Test
  public void home() throws Exception {
    mockMvc.perform(get("/home"))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(forwardedUrl("/jsp/view/application.jsp"))
        .andExpect(content().string("Welcome"));
  }

And it is failing java.lang.AssertionError: Response content expected:<Welcome> but was:<>

the printed out response is the following:

MockHttpServletResponse:
              Status = 200
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = /jsp/view/application.jsp
      Redirected URL = null
             Cookies = []

Environment:

  • Spring 3.2
  • Tiles 2
  • Java 6

What have I missed?

NB: The code is working in Tomcat with real browser.


回答1:


You cannot write assertions for the content of a JSP page because JSP pages are rendered by a servlet container and Spring MVC Test doesn't run a servlet container. You can only verify that the view name is correct and/or the request is forwarded to the correct url.

However, you can write assertions for the content of your views if you use a view technology that doesn't require a servlet container (such as Velocity or Thymeleaf).



来源:https://stackoverflow.com/questions/28944538/empty-content-in-spring-mvc-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!