Jason Whittle
Jason Whittle

Reputation: 805

Do I need to create a new MockMvc for each test?

I’m attempting to add Cucumber to my Spring Web MVC project which is already using spring-test and JUnit. The non-Cucumber integration tests I’ve already written have the WebApplicationContext autowired in, then created a MockMvc for each test. The Cucumber example I’m trying to work from injects a MockMvc once for the lifetime of the step definition class.

The API docs for MockMVC don’t give any guidance on how calling perform modifies a MockMvc instance, and whether it’s acceptable to reuse a MockMvc instance for multiple tests. I also wasn’t able to find a definite answer in the reference docs.

What is the contract with MockMvc? Should I be creating a new one for each test?

Upvotes: 3

Views: 2207

Answers (2)

user3151168
user3151168

Reputation:

Take a look at the instance variables of MockMvc and you may be able to deduce a answer.

static String MVC_RESULT_ATTRIBUTE = MockMvc.class.getName().concat(".MVC_RESULT_ATTRIBUTE");

private final TestDispatcherServlet servlet;

private final Filter[] filters;

private final ServletContext servletContext;

private RequestBuilder defaultRequestBuilder;

private List<ResultMatcher> defaultResultMatchers = new ArrayList<ResultMatcher>();

private List<ResultHandler> defaultResultHandlers = new ArrayList<ResultHandler>();

Instance/class variables MVC_RESULT_ATTRIBUTE and TestDispatcherServlet are thread-safe and filters and servletContext are only set during initialization. filters and servletContext should be thread-safe and stateless, too. defaultRequestBuilder, defaultResultMatchers and defaultResultHandlers have a setter method. From a technical point of view MockMvc is not thread-safe and shouldn't be reused. These setters are package private and a MockMvc instance can be acquired only through MockMvcBuilders. Hence you can't manipulte a MockMvc instance afterwards so that it is actually resuable across multiple tests.

Upvotes: 3

Rossen Stoyanchev
Rossen Stoyanchev

Reputation: 5018

MockMvc can be created once and used for any number of requests.

Upvotes: 3

Related Questions