3

I want to use MockMvc without SpringJUnit4ClassRunner.

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

Since main is not invoked by a springcontainer how do I create a WebApplicationContext?

Is something like the following not-working pseudocode possible?

 WebApplicationContext wac = new WebApplicationContext("classpath./service-context.xml");
jack
  • 1,861
  • 4
  • 31
  • 52

1 Answers1

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)

Sam Brannen
  • 29,611
  • 5
  • 104
  • 136