我发现,取消注释测试监听器注释会导致下面的测试无法正常工作( Autowiring 成员未初始化并且发生 NullPointerException):
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestExecutionListenerTry2._Config.class)
//@TestExecutionListeners({TestExecutionListenerTry2._Listener.class})
public class TestExecutionListenerTry2 {
public static class Bean1 {
{
System.out.println("Bean1 constructor");
}
public void method() {
System.out.println("method()");
}
}
@Configuration
public static class _Config {
@Bean
public Bean1 bean1() {
return new Bean1();
}
}
public static class _Listener extends AbstractTestExecutionListener {
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
System.out.println("prepareTestInstance");
}
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
System.out.println("beforeTestClass");
}
}
@Autowired
public Bean1 bean1;
@Test
public void testMethod() {
bean1.method();
}
}
为什么?
最佳答案
当您提供@TestExecutionListeners
注释时,您将覆盖默认列表TestExecutionListener
类型,其中包括 DependencyInjectionTestExecutionListener
处理依赖注入(inject)。
默认类型在 TestExecutionListener
javadoc 中声明:
Spring provides the following out-of-the-box implementations (all of which implement
Ordered
):
ServletTestExecutionListener
DependencyInjectionTestExecutionListener
DirtiesContextTestExecutionListener
TransactionalTestExecutionListener
SqlScriptsTestExecutionListener
也可以注册这些。或者使用 Spring documentation 中概述的技术合并您的设置和默认值。
To avoid having to be aware of and re-declare all default listeners, the
mergeMode
attribute of@TestExecutionListeners
can be set toMergeMode.MERGE_WITH_DEFAULTS
.MERGE_WITH_DEFAULTS
indicates that locally declared listeners should be merged with the default listeners.
所以你的注释看起来像
@TestExecutionListeners(value = { TestExecutionListenerTry2._Listener.class },
mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
关于java - 如果在 JUnit 和 Spring 中使用测试监听器, Autowiring 将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32978691/