【问题标题】:Spring MVC test with MockMvc使用 MockMvc 进行 Spring MVC 测试
【发布时间】:2013-07-06 17:49:28
【问题描述】:

我正在尝试运行测试以测试 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”。

请帮忙!

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我的 ContextConfiguration 错误。正确的是:

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

      现在一切正常。

      【讨论】:

      • @jorgen 你能提供你的 applicationContext.xml 和 serviceContext.xml 文件的内容吗?
      猜你喜欢
      • 1970-01-01
      • 2015-03-29
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 2014-05-31
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多