Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop JUnit test in @Before method without failing

Tags:

java

junit

These are my testcases

class Mother {

    @Before
    public void setUp() {
        if (!this.getClass().isAnnotatedWith("Version20")) { // pseudo code
            /*
             * stop this test without failing!
             */
        }

        // further setup
    }
}


@Version20
class Child extends Mother {

    @Test
    public void test() {
        // run only when Version == 20
    }
}

Is it possible to stop the test in Child in the @Before method of Mother without failing or assertTrue(false)?

edit: I have more Versions @Version19, @Version18 etc. my software is reading a configfile and outputting the result some tests are only applicable for special Versions. I don't want to make the version check within the test method because i have a lot of small tests and don't like code duplication

like image 421
Absurd-Mind Avatar asked May 02 '12 11:05

Absurd-Mind


People also ask

How do I stop JUnit testing?

A second option would be to disable tests temporarily using the JUnit @Ignore annotation. We can add it at the class level to disable all tests in a class: @Ignore("Class not ready for tests") public class IgnoreClassUnitTest { @Test public void whenDoTest_thenAssert() { // ... } }

Can you ignore a test based on runtime information?

OK, so the @Ignore annotation is good for marking that a test case shouldn't be run. However, sometimes I want to ignore a test based on runtime information. An example might be if I have a concurrency test that needs to be run on a machine with a certain number of cores.

Which annotation helps you to disable a test method?

JUnit 5 – @Disabled Annotation You may disable or skip execution for a test method or a group of tests by applying the annotation at the Test level. Or all the tests could be skipped by applying @Disabled annotation at the class level instead of applying it to the test method level.


1 Answers

I asked a similar question previously - the result was that you can use the Assume class' methods to disable a test based on a run-time check (whereas @Ignore is a static condition).

That said, if you're always disabling them based on a specific annotation, it would seem that you don't actually need to do this at run-time. Simply annotating the classes with @Ignore as well as @Version20 would do the job, and would be arguably clearer.

Though I suspect you might be ignoring only if the test is running in "1.0 mode" - in which case it is a runtime introspection, and you could do this with something like:

@Before
public void setUp() {
   if (!this.getClass().isAnnotatedWith("Version20")) {
      final String version = System.getProperty("my.app.test.version");
      org.junit.Assume.assumeTrue(version.equals("2.0"));
   }
}
like image 118
Andrzej Doyle Avatar answered Oct 08 '22 04:10

Andrzej Doyle