2

Can Mockmvc be reused within a test suite? I have several test suites so having to initialize the mockmvc between every test and then running all tests is really slow!

I've tried putting mockMvc into the annotation @BeforeClass rather than in @Before but because it is a static method, the WebApplicationContext and FilterChainProxy are autowired so cannot be referenced in a static method as far as I'm aware.

My tests are currently set up like:

@ContextConfiguration(classes = {Application.class})
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class MyTest {

  @Autowired
  private static WebApplicationContext wac;

  @Autowired
  private static FilterChainProxy springSecurityFilter;

  private MockMvc mockMvc;

  @Before
  public void setUp() {
      assertNotNull(wac);
      assertNotNull(springSecurityFilter);

      this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilters(springSecurityFilter).build();
  }

Does anyone know how/if it is possible to reuse Mockmvc? It seems like an expensive operation to set up and tear down for every test.

Any help would be much appreciated, thanks.

diepjy
  • 283
  • 2
  • 10

1 Answers1

1

How about a @Before method which doesn't overwrite the mockMvc if it is set.

private static MockMvc mockMvc = null;

@Before
public void setUp() {
    assertNotNull(wac);
    assertNotNull(springSecurityFilter);

    if (this.mockMvc == null) {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilters(springSecurityFilter).build();
    }
}
mikeapr4
  • 2,830
  • 16
  • 24
  • But `mockmvc` gets teared down after each test so it will get set to null again and get reinitialised. Also, I think you meant `this.mockMvc == null`? – diepjy Feb 24 '17 at 09:23
  • fixed the null check, also forgot static on the MockMvc member. I've tested it, it'll only initialise the mockMvc once. – mikeapr4 Feb 24 '17 at 11:30
  • I added a print statement in the if statement, but the print statement gets executed at every test within the test suite – diepjy Feb 24 '17 at 12:01
  • I'm using Spring v4.2.5, JUnit v4.12 and Java 1.8.0_51 - I have 7 tests in my suite and the line constructing the mockMvc is only hit once, I have a breakpoint on it. – mikeapr4 Feb 24 '17 at 12:48
  • i'm faced with the same problem. It is useless to check mockMvc on null, since mockMvc will instantiated everytime in @Before methods, cause is everytime null – Roma Kap Jan 12 '21 at 14:34