如何使用 MockMvc 访问 DispatcherServlet?

How do I access DispatcherServlet with MockMvc?

我有一个基本的 SpringMVC 应用程序,运行宁(和映射)很好。 现在我想用 MockMvc 设置我的单元测试来执行获取请求和东西。 但是如果我 运行 测试有一个 AssertionError "Status expected: <200> but was: <404>" 并且我的控制台给出警告 "No mapping found for HTTP request with URI [/] in DispatcherServlet with name ''"。 我感觉我的 MockMvc 无法与我的 DispatcherServlet 通信,那么我该如何定义这个连接?

这是我的简短测试class:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class HomeControllerTest {

  private MockMvc mvc;
  @Autowired
  private WebApplicationContext wac;

  @Before
  public void setup() throws ServletException {
    mvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }

  @Test
  public void testLandingPagePath() throws Exception {
    mvc.perform(get("/")).andExpect(status().isOk());
  }
}

所以我希望 MockMvc 默认获取我的 DispatcherServlet 的位置。但它实际上并没有调用它进行映射。

我的 "web.xml" 和 "dispatcher-servlet.xml" 位于 "WEB-INF" 文件夹中,没有定义额外的配置。

我感觉问题出在我的项目结构上,但这是一个基本的 eclipse "Dynamic Web Application",测试位于 "src/test/java",平行于 "src/main/java"。

感谢任何帮助,因为我花了最后 2 个小时阅读解决方案,但没有找到窍门。

又过了一段时间,我现在得到了一些东西: 我仍然无法访问 WEB-INF 文件夹中的 dispatcher-servlet.xml。我在我的 test-package 中添加了一个新的 "config" 包,与我的 "controller" 测试包并行,并在其中放置了一个 dispatcher-servlet.xml 的副本,称为 "test-dispatcher-servlet.xml".

现在我的测试 class 可以通过

访问它
@ContextConfiguration("../config/test-dispatcher-servlet.xml")
public class HomeControllerTest {

希望这可以帮助其他开始 spring mvc 测试的人:-)