集成测试

时间:2016-06-06 14:10:20

标签: java spring junit integration-testing maven-failsafe-plugin

我使用Spring和JUnit编写了集成测试。我添加了一个@Before方法来设置mockMvc。代码如下所示:

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

IntelliJ中的结果很不稳定,但每当我使用maven failafe运行测试时,我都会收到以下错误:

  

java.lang.IllegalArgumentException:需要WebApplicationContext

此异常抛出webAppContextSetup()的行。记录webContext变量时,该变量在4次测试中有3次为空。它中的1个(随机变化)已设置。

当我研究这个问题时,每个人都说我应该添加@WebAppConfiguration注释,就在那里。

有关其他信息,我的AppConfig类如下所示:

@Configuration
@EnableAspectJAutoProxy
@EnableAsync
@EnableWebMvc
@EnableWebSecurity
@ComponentScan
public class AppConfig extends WebMvcConfigurerAdapter {
    @Autowired
    Environment environment;
}

希望任何人都可以提供帮助。谢谢!

0 个答案:

没有答案
相关问题