TestExecutionListener根本不监听

时间:2018-09-09 12:40:59

标签: spring spring-test applicationcontext spring-bean spring-config

我有自定义的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是如何创建的。可能有人可以解释吗?)但是即使那样,它至少也应该转到lestener中的beforeTestMethod吗?还是不?

第二个问题:如果它确实没有封装我的appContext,我该如何解决?即将我的appContext设置为testContext.getApplicationContext()?我需要像appContext一样从我的testContext.getApplicationContext().getBean(...)提取豆子。

2 个答案:

答案 0 :(得分:1)

对于初学者,只有在使用 Spring TestContext Framework (TCF)时,才支持TestExecutionListener

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

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

一般来说,我建议您阅读《 Spring参考手册》的Testing chapter,如果这样做还不够用,您当然可以在线找到“与Spring集成测试”的教程。

此致

Sam(Spring TestContext Framework的作者

答案 1 :(得分:0)

您尝试过@Before吗?这不是必需的静态方法?

private static ApplicationContext appContext;

@Before
public void init() {
    if(appContext == null) {
        appContext = new AnnotationConfigWebApplicationContext();
        // register some configs for context here
     }
}
相关问题