Empty content in spring mvc test

I could not verify the contents of the page using the spring mvc test because it is empty.

The indicated simplest possible controller:

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

appropriate tile configurations:

 <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 fails java.lang.AssertionError: Response content expected:<Welcome> but was:<>

the printed answer is as follows:

 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 did I miss?

NB: the code works in Tomcat with a real browser.

+6
source share
1 answer

You cannot write statements for the contents of a JSP page because JSP pages are rendered by the servlet container and Spring MVC Test does not start the servlet container. You can only verify that the view name is correct and / or the request is redirected to the correct URL.

However, you can write statements for the contents of your views if you use viewing technology that does not require a servlet container (such as Velocity or Thymeleaf).

+5
source

Source: https://habr.com/ru/post/983534/


All Articles