Java 使用 Maven 运行 JUnit 测试时,Spring MockMvc WebApplicationContext 为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18899152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:07:38  来源:igfitidea点击:

Spring MockMvc WebApplicationContext is null when running JUnit Tests with Maven

javamaventestingspring-mvcjunit

提问by Ayub Malik

I have a Spring mock-mvc JUnit test class that contains two tests. When I run the tests within Eclipse IDE both tests pass(I use Eclipse Maven plugin).

我有一个包含两个测试的 Spring mock-mvc JUnit 测试类。当我在 Eclipse IDE 中运行测试时,两个测试都通过了(我使用 Eclipse Maven 插件)。

When running the tests from the command line using

从命令行运行测试时使用

mvn test

one of the tests fails because the WebApplicationContext that is @Autowired is sometimesnull.

其中一项测试失败,因为 @Autowired 的 WebApplicationContext有时为空。

Here is my test class

这是我的测试课

@WebAppConfiguration
@ActiveProfiles({ "dev", "test" })
public class AddLinkEndpointMvcTest extends BaseMvc {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void before() {
        System.out.println("WAC = " + wac);
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void addLinkDoesNotSupportGet() throws Exception {
        mockMvc.perform(get("/myurl")).andExpect(status().is(HttpStatus.SC_METHOD_NOT_ALLOWED));
    }

    @Test
    public void addLinkBadRequestNoLinkAddress() throws Exception {
        mockMvc.perform(post("/myurl")).andExpect(status().is(HttpStatus.SC_BAD_REQUEST));
    }
}

Here is the BaseMvc class

这是 BaseMvc 类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class BaseMvc {

    @Configuration
    @ComponentScan(basePackages = { "com.example.a", "com.example.b" })
    @Profile("test")
    public static class TestConfig {

        static {
            System.out.println("TEST CONFIG");
        }

        // ...some beans defined here

        @Bean
        public static PropertySourcesPlaceholderConfigurer properties() {
            PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
            configurer.setIgnoreUnresolvablePlaceholders(false);
            configurer.setLocations(new Resource[] { new ClassPathResource("sample-webapp.properties"),
                new ClassPathResource("sample-domain.properties") });
            return configurer;
        }

    }

}

I have added the println calls to aide debugging. When running mvn test here is the relevant console output:

我已经添加了 println 调用来帮助调试。在这里运行 mvn test 是相关的控制台输出:

WAC = null
WAC = org.springframework.web.context.support.GenericWebApplicationContext@38795184: startup date [Thu Sep 19 16:24:22 BST 2013]; root of context hierarchy

and the error

和错误

java.lang.IllegalArgumentException: WebApplicationContext is required
        at org.springframework.util.Assert.notNull(Assert.java:112)
        at org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder.<init>(DefaultMockMvcBuilder.java:66)
        at org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup(MockMvcBuilders.java:46)
        at com.mypackage.AddLinkEndpointMvcTest.before(AddLinkEndpointMvcTest.java:31)

So this is the problem line in the test

所以这是测试中的问题行

@Autowired
private WebApplicationContext wac;  

Sometimes wac is null or has not completed initialisation before the JUnit @Before kicks in.

有时 wac 为空或在 JUnit @Before 启动之前尚未完成初始化。

What I don't understand is the WebApplicationContext is sometimes null and why it passes in Eclipse IDE!

我不明白的是 WebApplicationContext 有时为 null 以及为什么它会在 Eclipse IDE 中传递!

回答by Mike Rylander

Try using getBean instead of auto wiring. This should assure that WebApplicationContextis initialized when you access it.

尝试使用 getBean 而不是自动连接。这应该确保WebApplicationContext在您访问它时已初始化。

Example:

例子:

MyClass myClass = applicationContext.getBean("myClass");

回答by user3777313

Please use @WebAppConfiguration annotation. Your question is already answered here : WebApplicationContext doesn't autowire

请使用@WebAppConfiguration 注解。您的问题已在此处得到解答:WebApplicationContext 不会自动装配