0

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!

Hans Leautaud
  • 1,742
  • 1
  • 19
  • 34
  • You're missing the spring test runner. – Sotirios Delimanolis Jun 06 '16 at 14:12
  • Good catch, but that was just a copy-paste error unfortunately. One is successful, the rest is still failing: Tests in error: TestControllerTest.setUp:38 » IllegalArgument WebApplicationContext is require... TestControllerTest.setUp:38 » IllegalArgument WebApplicationContext is require... TestControllerTest.setUp:38 » IllegalArgument WebApplicationContext is require... Tests run: 6, Failures: 0, Errors: 3, Skipped: 2 – Hans Leautaud Jun 06 '16 at 14:27
  • Please provide a [MCVE]. – Sotirios Delimanolis Jun 06 '16 at 14:29

0 Answers0