gpt4 book ai didi

java - TestExecutionListeners 注释防止连接 spring bean

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:41:37 25 4
gpt4 key购买 nike

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

我的测试类看起来像:

@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());
}
}

应用测试监听器:

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 上失败。发生了什么事?

最佳答案

对于初学者来说,不幸的是,cassandra-unit 示例并不是一个很好的示例,因为它会导致您遇到的问题。

When I remove the @TestExecutionListeners annotation in MyTest the test finishes as expected, but leaving that annotation makes the unittest fail on the assertNotNull. What is happening?

当你在一个测试类上声明 @TestExecutionListeners(AppTestListener.class) 时,它不会扩展任何其他用 @TestExecutionListeners 注释的测试类,你实际上是在告诉 Spring 加载您的AppTestListener,当您实际想要将AppTestListener与来自Spring的默认监听器结合使用时(例如,DependencyInjectionTestExecutionListener 添加了对来自 ApplicationContext 的 bean 依赖注入(inject)的支持。

详情请阅读全文TestExecutionListener configuration Spring 引用手册的一部分。

这是解决您的问题的方法。

Spring Framework 4.1 之前

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners({
CassandraUnitTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class
})
@CassandraUnit
public class MyCassandraUnitTest {

@Test
public void xxx_xxx() {
}
}

Spring Framework 4.1之后

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners(
listeners = CassandraUnitTestExecutionListener.class,
mergeMode = MERGE_WITH_DEFAULTS
)
@CassandraUnit
public class MyCassandraUnitTest {

@Test
public void xxx_xxx() {
}
}

问候,

Sam(Spring TestContext Framework 的作者)

附注我创建了一个 issue for Cassandra Unit以便他们在示例中解决这个问题。

关于java - TestExecutionListeners 注释防止连接 spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32286540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com