TestExecutionListener根本没有监听

问题描述 投票:0回答:2

我有自定义TestExecutionListener:

public class CustomExecutionListener extends AbstractTestExecutionListener {
    @Override
    public void beforeTestMethod(TestContext testContext) throws Exception { 
        // some code ...
    }

    @Override
    public void afterTestMethod(TestContext testContext) throws Exception {
        // some code ...
    }
}

在我的测试类中,我将其配置如下:

@TestExecutionListeners({
    DirtiesContextTestExecutionListener.class,
    DependencyInjectionTestExecutionListener.class,
    CustomExecutionListener.class
})
class MyTestClass {

    private static ApplicationContext appContext;

    @BeforeAll
    static void init() {
        appContext = new AnnotationConfigWebApplicationContext();
        // register some configs for context here
    }

    @Test
    void test() {
    }
}

并且CustomExecutionListener不起作用 - 在调试器中我甚至不去那里。我想这可能是我创建ApplicationContext的方式的问题:可能是TestContext封装不是我的appContext? (我没有正确理解TestContext是如何创造的。可能有人可以解释一下吗?)但即便如此,它应该至少去找一个beforeTestMethod在lestener?或不?

第二个问题:如果它真的封装了我的appContext我怎么能解决这个问题? I. e。把我的appContext设为testContext.getApplicationContext()?我需要能够像appContext那样从我的testContext.getApplicationContext().getBean(...)中提取豆子。

spring spring-test applicationcontext spring-bean spring-config
2个回答
1
投票

首先,只有在使用Spring TestContext Framework(TCF)时才支持TestExecutionListener

由于您使用的是JUnit Jupiter(a.k.a。,JUnit 5),因此您需要使用@ExtendWith(SpringExtension.class)@SpringJUnitConfig@SpringJUnitWebConfig注释您的测试类。

此外,您不应该以编程方式创建您的ApplicationContext。相反,您让TCF为您执行此操作 - 例如,通过@ContextConfiguration@SpringJUnitConfig@SpringJUnitWebConfig以声明方式指定要使用的配置类。

一般来说,我建议你阅读Spring参考手册的Testing chapter,如果这样做不够,你肯定可以在线找到“使用Spring进行集成测试”的教程。

问候,

Sam(Spring TestContext Framework的作者)


0
投票

你有没有尝试过@Before静态方法?

private static ApplicationContext appContext;

@Before
public void init() {
    if(appContext == null) {
        appContext = new AnnotationConfigWebApplicationContext();
        // register some configs for context here
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.