2017-02-13 26 views
5

Jak mogę użyć wstrzyknięcia zależności Spring do klasy TestExecutionListener, którą napisałem rozszerzając AbstractTestExecutionListener?Wstrzyknięcie zależności sprężynowych w Spring TestExecutionListeners nie działa

Wiosna DI nie działa z klasami TestExecutionListener. Przykład wydania:

AbstractTestExecutionListener:

class SimpleClassTestListener extends AbstractTestExecutionListener { 

    @Autowired 
    protected String simplefield; // does not work simplefield = null 

    @Override 
    public void beforeTestClass(TestContext testContext) throws Exception { 
     System.out.println("simplefield " + simplefield); 
    } 
} 

plik konfiguracyjny:

@Configuration 
@ComponentScan(basePackages = { "com.example*" }) 
class SimpleConfig { 

    @Bean 
    public String simpleField() { 
     return "simpleField"; 
    } 

} 

Plik JUnit Test:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = { SimpleConfig.class }) 
@TestExecutionListeners(mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS, listeners = { 
    SimpleClassTestListener.class }) 
public class SimpleTest { 

    @Test 
    public void test(){ 
     assertTrue(); 
    } 
} 

Jak podkreślono w komentarzu kodu, kiedy uruchom to, wydrukuje "simplefield null", ponieważ simplefield nigdy nie g ets wstrzyknięto wartość.

+0

Dodałem również @ComponentScan (basePackages = {"com.example *"}) w konfiguracji. –

+0

Nie lubię używać testContext.getApplicationContext(). GetBean (...). –

+0

Widzę ten problem również w nowym projekcie z Spring Boot 1.5.2.RELEASE. –

Odpowiedz

2

Wystarczy dodać autowiring dla całego obiektu TestExecutionListener.

@Override 
public void beforeTestClass(TestContext testContext) throws Exception { 
    testContext.getApplicationContext() 
      .getAutowireCapableBeanFactory() 
      .autowireBean(this); 
    // your code that uses autowired fields 
} 

Sprawdź sample project in github.