使用MockMvc进行Spring MVC测试

时间:2013-07-09 07:53:25

标签: java spring unit-testing mocking spring-mvc-test

我正在尝试运行测试Spring MVC控制器的测试。测试编译并运行,但我的问题是我收到了一个PageNotFound警告:

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

我的测试非常简单如下:

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"));       
  }
}

我100%确定我的webapp映射到“/”的首页,并且视图上的名称是“searchfrontpage”。

请帮忙!

2 个答案:

答案 0 :(得分:5)

我的ContextConfiguration错了。正确的是:

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

现在一切正常。

答案 1 :(得分:1)

另一种解决问题的简单方法是将init更改为:

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