如果在 JUnit & Spring 中使用测试侦听器,则自动装配不起作用

Autowiring is not working if test listener used in JUnit & Spring

我发现,取消注释测试侦听器注释会导致下面的测试无法正常工作(自动装配的成员未初始化并且出现 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 types, which includes a DependencyInjectionTestExecutionListener 处理依赖项注入的默认列表。

默认类型在 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 to MergeMode.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)