简体   繁体   中英

junit detect if a test is the only one run

I have a test like this:

@Test public void testInfinite() {
    while (true) {runSomeOtherTest();waitForSomeSignal();}

We have a spring context which takes a while to initialize - and with the above test and hotswapping - it means I can debug changes in seconds rather than waiting for a restart.

However, obviously checking this into the CI system is a bit of a problem, and of course something I've accidentally done several times. I'm wondering if it's possible (without changing the testrunner, because we are already using a custom one, that's hard to modify) to determine if it's the only test running. eg I want to be able to say

@Test public void testInfinite() {
    if (!testIsTheOnlyTestWhichWillBeRun()) return; ...

So, bottom line - what I'm looking for is that if I right click on exactly that test and say run, in the IDE - it will do that - in all other cases - eg I right click and run the whole class - or I do it from gradle, or from CI - the test does nothing and just returns immediately.

You can evaluate a System property:

@Test public void testInfinite() {
    if (!"true".equals(System.getProperty("junit.runloop"))) {
        return;
    }
}

In your IDE/local run, you can then run the test with -Djunit.runloop=true.

To not polute the test cases themselves, you could write a JUnit rule that does this:

public class TestInfinite implements TestRule {
    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {
            public void evaluate() throws Throwable {
                    do {
                        base.evaluate();
                    } while ("true".equals(System.getProperty("junit.runloop")));
            }
        };
    }
}

So in your test, you can attach them:

public class YourTest {
    @Rule public TestInfinite = new TestInfinite();

    @Test public void testInfinite() {
        // this will be run once if property is not set,
        // in an endless loop if it is
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM