Spring MVC Test with MockMvc

I am trying to run a test to test Spring MVC controller. The test compiles and runs, but my problem is that I received a PageNotFound warning:

WARN PageNotFound - No mapping found for HTTP request with URI [/] in DispatcherServlet with name '' 

My really simple test:

 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({ "classpath*:/WEB-INF/applicationContext.xml", "classpath*:/WEB-INF/serviceContext.xml" }) public class FrontPageControllerTest { @Autowired private WebApplicationContext ctx; private MockMvc mockMvc; @Before public void init() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.ctx).build(); } @Test public void frontPageController() throws Exception { this.mockMvc.perform(get("/")) .andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("searchfrontpage")); } } 

I am 100% sure that my webapp maps to the main page on the "/" page and that the name in the "search page" view.

Please, help!

+6
source share
2 answers

My ContextConfiguration configuration was incorrect. It was right:

 @ContextConfiguration({ "file:src/main/webapp/WEB-INF/applicationContext.xml", "file:src/main/webapp/WEB-INF/serviceContext.xml" }) 

Now everything is working fine.

+5
source

Another easy way to solve the problem is to change init to this:

 mockMvc = MockMvcBuilders.standaloneSetup(new FrontPageController()).build(); 
0
source

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


All Articles