1

I found, that uncommenting test listener annotation causes test not working below (autowired member is not initialized and NullPointerException occurs):

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

Why?

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

4

When you provide a @TestExecutionListeners annotation, you overwrite the default list of TestExecutionListener types, which includes a DependencyInjectionTestExecutionListener that handles dependency injection.

The default types are declared in the TestExecutionListener javadoc:

Spring provides the following out-of-the-box implementations (all of which implement Ordered):

  • ServletTestExecutionListener
  • DependencyInjectionTestExecutionListener
  • DirtiesContextTestExecutionListener
  • TransactionalTestExecutionListener
  • SqlScriptsTestExecutionListener

Either register those as well. Or merge yours and the defaults with the technique outlined in the 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.

So your annotation would look like

@TestExecutionListeners(value = { TestExecutionListenerTry2._Listener.class },
        mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • I'm getting the null exception on a member in my TestExecutionListener even when using the MergeMode.MERGE_WITH_DEFAULTS, like this question: http://stackoverflow.com/questions/42204840/spring-dependency-injection-into-spring-testexecutionlisteners-not-working What's the difference? – k-den Mar 31 '17 at 15:41