【问题标题】:Is it possible to use MockMvc without SpringJUnit4ClassRunner?是否可以在没有 SpringJUnit4ClassRunner 的情况下使用 MockMvc?
【发布时间】:2014-07-17 09:51:06
【问题描述】:

我想在没有 SpringJUnit4ClassRunner 的情况下使用 MockMvc。

   public static void main(String[] args) {
     WebApplicationContext wac = ...;
     MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
   }

由于 main 没有被 springcontainer 调用,我该如何创建 WebApplicationContext?

是否可能出现类似以下不工作的伪代码?

 WebApplicationContext wac = new WebApplicationContext("classpath./service-context.xml");

【问题讨论】:

    标签: spring spring-mvc spring-test spring-test-mvc


    【解决方案1】:

    创建MockMvc实例主要有两种方式:

    1. 来自WebApplicationContext,通过Spring TestContext 框架(例如,使用@ContextConfiguration@WebAppConfiguration)或手动加载。
    2. 在独立模式下使用 @Controller 类。

    这两个都记录在参考手册的测试一章的Setup Options 部分中。

    要创建WebApplicationContext手动,实例化GenericWebApplicationContext 并从 XML 文件中加载 bean 定义,如下所示:

    GenericWebApplicationContext context = new GenericWebApplicationContext();
    new XmlBeanDefinitionReader(context).loadBeanDefinitions(/* XML config files */);
    context.refresh();
    

    或者来自@Configuration 这样的类:

    GenericWebApplicationContext context = new GenericWebApplicationContext();
    new AnnotatedBeanDefinitionReader(context).register(/* @Configuration classes */);
    context.refresh();
    

    请注意,您还需要在context 中配置和设置MockServletContext

    问候,

    Sam(Spring TestContext 框架的作者)

    【讨论】:

      猜你喜欢
      • 2014-06-16
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多