Ayu*_*lik 6 java testing junit spring-mvc maven
我有一个Spring mock-mvc JUnit测试类,它包含两个测试.当我在Eclipse IDE中运行测试时,两个测试都通过(我使用Eclipse Maven插件).
使用时从命令行运行测试
mvn test
Run Code Online (Sandbox Code Playgroud)
其中一个测试失败,因为@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));
}
}
Run Code Online (Sandbox Code Playgroud)
这是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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我已经添加了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
Run Code Online (Sandbox Code Playgroud)
和错误
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)
Run Code Online (Sandbox Code Playgroud)
所以这是测试中的问题
@Autowired
private WebApplicationContext wac;
Run Code Online (Sandbox Code Playgroud)
有时wac为null或在JUnit @Before开始之前尚未完成初始化.
我不明白的是WebApplicationContext有时是null,为什么它在Eclipse IDE中传递!
Mik*_*der -3
尝试使用 getBean 而不是自动装配。这应该确保WebApplicationContext您访问它时已初始化。
例子:
MyClass myClass = applicationContext.getBean("myClass");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10536 次 |
| 最近记录: |