I wrote integration tests using Spring and JUnit. I added a @Before method to setup the mockMvc. The code looks like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigWebContextLoader.class)
@WebAppConfiguration
public class TestControllerTest {
@Autowired
WebApplicationContext webContext;
private MockMvc mockMvc;
private String requestUrl = "/v1/tests/1";
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(this.webContext).apply(springSecurity()).build();
}
@Test
public void getTest_noAuthenticationHeaderProvided_returnsUnauthorizedHttpStatus() throws Exception {
mockMvc.perform(get(requestUrl)).andExpect(status().isUnauthorized());
}
}
The results in IntelliJ are flaky, but every time when I run the tests with maven failsafe, I get the following error:
java.lang.IllegalArgumentException: WebApplicationContext is required
This exception is thrown on the line of the webAppContextSetup(). When log the webContext variable, the variable is null in 3 out of 4 tests. 1 out of 4 (which changes randomly) it is set.
When I research the problem, everybody is saying that I should add the @WebAppConfiguration annotation, which is there.
For additional information, my AppConfig class looks like this:
@Configuration
@EnableAspectJAutoProxy
@EnableAsync
@EnableWebMvc
@EnableWebSecurity
@ComponentScan
public class AppConfig extends WebMvcConfigurerAdapter {
@Autowired
Environment environment;
}
Hope anyone can help. Thanks!