jeudi 17 septembre 2020

How to execute some code using context before/after all tests with SpringExtension?

I need to execute some initialization/deinitialization code before/after all tests (in all classes) using DI container when SpringExtension is used. I tried two solutions:

@ExtendWith({BeforeAllAfterAll.class, SpringExtension.class})
@ContextConfiguration(classes = ContextConfig.class)
public class ServiceIT{..}

public class BeforeAllAfterAll implements BeforeAllCallback,
     ExtensionContext.Store.CloseableResource {...}

However, in BeforeAllAfterAll class I can't get reference to application context.

I tried to use events:

public class ContextEventHandler {
    
    @EventListener
    public void handleContextStartedEvent(ContextStartedEvent event) {
        System.out.println("Context Start Event received.");
    }
    
    @EventListener
    public void handleContextRefreshEvent(ContextRefreshedEvent event) {
        System.out.println("Context Refreshed Event received.");
    }
    
    @EventListener
    public void handleContextStoppedEvent(ContextStoppedEvent event) {
        System.out.println("Context Stopped Event received.");
    }
}

However, as I found out when SptringExtension is used StartedEvent and StoppedEvent are not fired.

Could anyone say how to do it? I use spring 5 and junit 5.

Aucun commentaire:

Enregistrer un commentaire