2015-10-06 47 views
1

我发现使用的测试监听器,即取消注释测试监听器注释将使得测试不低于工作(自动装配成员没有初始化NullPointerException异常发生时):自动装配不工作,如果使用JUnit和春天

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

为什么?

回答

2

当您提供@TestExecutionListeners注释时,将覆盖默认的TestExecutionListener类型列表,其中包括处理依赖注入的DependencyInjectionTestExecutionListener

的默认类型在TestExecutionListener的javadoc声明:

Spring提供下列出的现成的实现(所有的 它们实现Ordered):

  • ServletTestExecutionListener
  • DependencyInjectionTestExecutionListener
  • DirtiesContextTestExecutionListener
  • TransactionalTestExecutionListener
  • SqlScriptsTestExecutionListener

无论注册这些也是如此。或合并你与技术默认在Spring documentation

概述为了避免必须了解并重新申报所有默认监听器, 的@TestExecutionListenersmergeMode属性可以设置为 MergeMode.MERGE_WITH_DEFAULTSMERGE_WITH_DEFAULTS表示 本地声明的侦听器应该与默认的 侦听器合并。

所以,你的注释看起来像

@TestExecutionListeners(value = { TestExecutionListenerTry2._Listener.class }, 
     mergeMode = MergeMode.MERGE_WITH_DEFAULTS) 
+0

我得到空例外TestExecutionListener的我一个部件上,甚至使用MergeMode.MERGE_WITH_DEFAULTS时,这样的问题:http://stackoverflow.com/questions/42204840/spring-dependency-injection-into-spring-testexecutionlisteners-not-working有什么区别? –