【问题标题】:Is there anything like Spring TestExecutionListener for TestSuite?TestSuite 有没有类似 Spring TestExecutionListener 的东西?
【发布时间】:2016-10-25 10:32:45
【问题描述】:

目前我正在使用TestExecutionListener 进行测试,效果非常好

public class ExecutionManager extends AbstractTestExecutionListener {

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

    @Override
    public void afterTestClass(TestContext testContext) throws Exception {
        System.out.println("afterClass");
    }
}

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(ExecutionManager.class)
public final class TC_001 {

    @Test
    public void test() {
        System.out.println("Test_001");
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(ExecutionManager.class)
public final class TC_002 {

    @Test
    public void test() {
        System.out.println("Test_002");
    }
}

当我在测试套件中包含这些测试时,会为每个测试类执行beforeTestClass(TestContext testContext)afterTestClass(TestContext testContext) 方法,这很合乎逻辑:

@RunWith(Suite.class)
@Suite.SuiteClasses({
        TC_001.class,
        TC_002.class
})
public final class TS_001 {
}

有没有类似SuiteExecutionListener(套房为TestExecutionListener)之类的东西?

基本上我需要非静态 @BeforeClass@AfterClass 用于套件

在 ExecutionListener 中,我需要找出已启动的类:案例或套件。为此,我可以:

  • 分析StackTrace并获取调用类
  • 使用Reflection.getCallerClass(int i)(已弃用)
  • 将调用者类传递给ExecutionManager(顺便问一下,我该怎么做?是否可以像在Android Bundle 中一样将Object 放入TestContext?)

但我不太喜欢这些解决方案。 SuiteExecutionListener 更可取

谢谢

【问题讨论】:

    标签: java spring junit testcontext


    【解决方案1】:

    不,很遗憾,Spring TestContext Framework (TCF) 中没有 SuiteExecutionListener 这样的东西。

    TCF 未在套件级别与 JUnit 4 集成。

    如果你想在TestContext 中存储一些东西,这不是问题。 TestContext 实现了org.springframework.core.AttributeAccessor,因此您可以在TestContext 中存储属性。但是请注意,给定 TestContext 的生命周期与测试类相关。

    【讨论】:

    • 所以基本上,如果 TestContext 绑定到一个测试类,我不能使用它来管理来自 TestExecutionListener 的测试套件流,因为它对于每个测试用例来说都是不同的 TestContext。我说的对吗?
    • 另外,据我目前所见,我无法从测试套件访问 TestContext,但 ApplicationContext 可用。由于它可用,我可以在那里放置一些标志 bean 并从我的 ExecutionManager 中读取它。从理论上讲,它可以让我管理测试套件流程,因为 ApplicationContext 可能会被缓存。它看起来不太好,考虑到我无法在 ExecutionManager 中使用反射的附加事实,我没有看到其他选项:堆栈跟踪中根本不存在测试套件和测试类。如果有什么更方便我的目的,你能给我一个线索吗?谢谢
    • 回答你的第一个问题:是的,没错。 Spring 与 JUnit 4 Suite runner 无关。所以套件级别不支持TestExecutionListeners。
    • 如果您想管理测试套件流程(如您所说),您基本上必须扩展org.junit.runners.Suite 并添加您的自定义行为。
    • 要在您的自定义Suite 实现和它运行的测试类之间进行通信,您可以考虑使用ThreadLocal。这可能比反射或将一些 bean 存储在 可能 共享的 ApplicationContext 中更优雅。
    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多