Is there anything like Spring TestExecutionListene

2019-09-14 19:29发布

问题:

Currently for tests I'm using TestExecutionListener and it works just perfect

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");
    }
}

Test classes:

@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");
    }
}

When I include those tests in test suite, beforeTestClass(TestContext testContext) and afterTestClass(TestContext testContext) methods are executed for each test class, what is quite logical:

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

Is there anything like SuiteExecutionListener (TestExecutionListener for suites)?

Basically I need non-static @BeforeClass and @AfterClass for suite

OR

In ExecutionListener I need to find out what class has been launched: case or suite. For this purpose I can:

  • analyze StackTrace and get calling class
  • use Reflection.getCallerClass(int i) (which is deprecated)
  • pass caller class to ExecutionManager (By the way, how can I do that? Is it possible to put Object into TestContext like in Android Bundle?)

But I don't really like those solutions. SuiteExecutionListener is much more preferable

Thank you

回答1:

No, there is unfortunately no such thing as a SuiteExecutionListener in the Spring TestContext Framework (TCF).

The TCF does not integrate with JUnit 4 at the suite level.

If you want to store something in the TestContext, that's not a problem. TestContext implements org.springframework.core.AttributeAccessor, so you can store attributes in the TestContext. Note, however, that the lifecycle of a given TestContext is tied to a test class.