diepjy
diepjy

Reputation: 283

Reuse Spring Mockmvc in unit tests

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.

Upvotes: 2

Views: 1787

Answers (1)

mikeapr4
mikeapr4

Reputation: 2856

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();
    }
}

Upvotes: 1

Related Questions