3

I have some code that needs to run before and after my tests classes. It does not matter how many test classes are running in the middle, it has to run once and only once for the entire collection.

When I run in a suite, it is called at the start and end of the entire suite, this is working as expected, however, I want to be able to run a single test class. In this case, the test class needs to detect that it is running alone and start the pre/post test code.

Is this possible?

4

2 回答 2

7

我这样解决了这个问题:

MySuite我添加了这个:

    public static Boolean suiteRunning = false;
    @ClassRule
    public static ExternalResource triggerSuiteRunning = new ExternalResource() {
      @Override
      protected void before() throws Throwable {
        suiteRunning = true;
      }
    };

现在,在相关测试中,我知道该套件是否正在运行并且可以禁用测试:

    @BeforeClass
    public static void beforeClass() {
        Assume.assumeTrue(MySuite.suiteRunning);
    }
    // --- or ---
    @Test
    public static void test() {
        Assume.assumeTrue(MySuite.suiteRunning);
    }
于 2015-02-19T12:17:10.300 回答
1

您总是可以通过让该代码检测它是否已经运行、通过静态字段或其他方法来实现这一点,然后再次跳过运行。@BeforeClass然后,在每个测试中无条件地调用它。

调用该代码现在成为每个测试的先决条件的一部分,自定义代码只负责在必要时运行。

您可能会首先考虑其他方法来避免该问题:要么减少测试的环境依赖性,要么使代码自然具有幂等性。

于 2013-08-03T12:42:17.060 回答