【发布时间】:2015-08-29 13:24:19
【问题描述】:
在cassandra-unit with spring example 之后,我发现spring bean 没有连接到测试类中,导致空指针异常。我试图将问题最小化,发现它可能不是 Cassandra 部分,而是存在 @TestExecutionListeners 注释,以及 AbstractTestExecutionListener 扩展类。
org.springframework:spring-core:4.2.0.RELEASE (Also fails with 3.2.14.RELEASE).
org.springframework:spring-test:4.2.0.RELEASE
junit.junit:4.11
JVM vendor/version: Java HotSpot(TM) 64-Bit Server VM/1.8.0_40
MAC OS X 10.10.5
我的 TestClass 看起来像:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({ AppTestListener.class }) <-- OK when removed
@ContextConfiguration(classes = { TestConfiguration.class })
public class MyTest {
@Autowired
private MyService myService;
@Test
public void testMyService() {
Assert.assertNotNull(myService);
Assert.assertEquals("didit", myService.doIt());
}
}
AppTestListener:
public class AppTestListener extends AbstractTestExecutionListener {
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
System.out.println("test");
}
}
配置类没有什么特别的(配置xml也失败了):
@Configuration
public class TestConfiguration {
@Bean
public MyService myService() {
return new MyService();
}
}
当我在 MyTest 中删除 @TestExecutionListeners 注释时,测试按预期完成,但留下该注释会使单元测试在 assertNotNull 上失败。 发生了什么?
【问题讨论】:
标签: java spring spring-test