我有一个Spring模拟mvc JUnit测试类,它包含两个测试。当我在Eclipse 中运行测试时,两个测试都通过了(我使用Eclipse插件)。
从命令行运行测试时,使用
mvn test其中一个测试失败了,因为@Autowired的WebApplicationContext是,有时为null。
这是我的考试课
@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));
}
}下面是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;
}
}
}我添加了println调用以辅助调试。当运行mvn测试时,下面是相关的控制台输出:
WAC = null
WAC = org.springframework.web.context.support.GenericWebApplicationContext@38795184: startup date [Thu Sep 19 16:24:22 BST 2013]; root of context hierarchy和错误
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)所以这是测试中的问题线
@Autowired
private WebApplicationContext wac; 有时,wac是空的,或者在JUnit @开始之前还没有完成初始化。
我不明白的是,WebApplicationContext有时是空的,为什么它会在Eclipse中传递!
发布于 2021-02-01 03:47:37
您应该在测试类之前添加@SpringBootTest作为注释。如下所示:
@RunWith(SpringRunner.class)
@SpringBootTest发布于 2015-06-19 12:37:37
请使用@WebAppConfiguration注释。您的问题已经在这里得到了回答:WebApplicationContext doesn't autowire
发布于 2013-09-25 16:33:26
尝试使用getBean代替自动配线。这应该确保在您访问WebApplicationContext时初始化它。
示例:
MyClass myClass = applicationContext.getBean("myClass");https://stackoverflow.com/questions/18899152
复制相似问题