3

我想在没有 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");
4

1 回答 1

1

There are two main ways to create a MockMvc instance:

  1. From a WebApplicationContext, loaded either via the Spring TestContext Framework (e.g., using @ContextConfiguration and @WebAppConfiguration) or manually.
  2. In stand-alone mode using a @Controller class.

Both of these are documented in the Setup Options section in the Testing chapter of the reference manual.

To create a WebApplicationContext manually, instantiate a GenericWebApplicationContext and load the bean definitions from XML files like this:

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

Or from @Configuration classes like this:

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

Note that you'll want to configure and set a MockServletContext in the context as well.

Regards,

Sam (author of the Spring TestContext Framework)

于 2014-07-17T11:59:45.807 回答