Java TestExecutionListeners注释防止连接SpringBean
接下来,我发现Springbean没有连接到testclass中,从而导致nullpointer异常。我试图最小化这个问题,发现它可能不是Cassandra部分,而是存在一个Java TestExecutionListeners注释防止连接SpringBean,java,spring,spring-test,Java,Spring,Spring Test,接下来,我发现Springbean没有连接到testclass中,从而导致nullpointer异常。我试图最小化这个问题,发现它可能不是Cassandra部分,而是存在一个@TestExecutionListeners注释,以及一个AbstractTestExecutionListener扩展类 org.springframework:spring-core:4.2.0.RELEASE (Also fails with 3.2.14.RELEASE). org.springframework:
@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());
}
}
配置类中没有什么特殊的内容(对于配置xml,它也会失败):
当我在MyTest中删除@TestExecutionListeners注释时,测试将按预期完成,但保留该注释会使assertNotNull上的unittest失败。
发生了什么?对于初学者来说,不幸的是,cassandra单元示例并不是一个很好的示例,因为它会导致与您遇到的问题一样的问题 当我在MyTest中删除@TestExecutionListeners注释时 测试按预期完成,但保留该注释会使 assertNotNull上的unittest失败。发生了什么事 当您在一个测试类上声明
@TestExecutionListeners(AppTestListener.class)
时,该测试类不扩展任何其他用@TestExecutionListeners
注释的测试类,您实际上是在告诉Spring只加载您的AppTestListener
,当您确实希望将AppTestListener
与Spring中的默认侦听器结合使用时(例如,DependencyInjectionTestExecutionListener
,它添加了对ApplicationContext
中bean的依赖项注入的支持)
有关详细信息,请阅读Spring参考手册的整个章节
以下是如何解决您的问题
在Spring框架4.1之前
@RunWith(SpringJUnit4ClassRunner.class)
@上下文配置
@TestExecutionListeners({
CassandraUnitTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class
})
@卡桑德劳尼
公共类MyCassandraUnitTest{
@试验
公共无效xxx_xxx(){
}
}
在Spring框架4.1之后
@RunWith(SpringJUnit4ClassRunner.class)
@上下文配置
@TestExecutionListeners(
listeners=CassandraUnitTestExecutionListener.class,
mergeMode=使用默认值合并
)
@卡桑德劳尼
公共类MyCassandraUnitTest{
@试验
公共无效xxx_xxx(){
}
}
问候,
Sam(SpringTestContext框架的作者)
p、 我创建了一个示例,以便他们在示例中解决这个问题
public class AppTestListener extends AbstractTestExecutionListener {
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
System.out.println("test");
}
}
@Configuration
public class TestConfiguration {
@Bean
public MyService myService() {
return new MyService();
}
}