There are two main ways to create a MockMvc
instance:
- From a
WebApplicationContext
, loaded either via the Spring TestContext Framework (e.g., using @ContextConfiguration
and @WebAppConfiguration
) or manually.
- 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)