java - 如果在 JUnit 和 Spring 中使用测试监听器, Autowiring 将不起作用

标签 java spring junit4

我发现,取消注释测试监听器注释会导致下面的测试无法正常工作( 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 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)

关于java - 如果在 JUnit 和 Spring 中使用测试监听器, Autowiring 将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32978691/

相关文章:

java - Java中的谓词

java - HK2/Jersey 不注入(inject)非资源类

java - 没有这样的 bean 定义并且不可能创建 bean

java - jUnit 在测试中跳过注入(inject)模拟方法中的方法调用

java - 使用匹配器断言 Collection 包含 2 个具有相同属性的对象

junit - "Assert in junit.framework has been deprecated"- 接下来要使用什么?

java - 如何返回类 - 输入方法

java - 在android中使用默认语言格式化字符串

java - 即使服务器停机,每 2 个月在第一天安排一个进程的最佳方法

java - Spring Boot with Swagger - 看不到我的 JpaRepository