Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUNIT Conditional Tests possible?

Tags:

java

junit

I have a series of data each one containing info_A and info_B. I would like to:

if(info_A) {
  run Test A
} else if(!info_A) {
  run Test B
}

It is very important that only the Test actually run is shown in the JUnit GUI tree. How can I do this?

The following solutions do not work:

  • If I use the Assume.assumeTrue(conditon), I can Ignore a test but then it is still displayed as passed in the test.
  • Doing this:
    Result result = JUnitCore.runClasses(TestStep1.class);
    leads to the correct result but the JUnit tree is not built.
  • Using @Catagories also shows the failed tests, which is also what I don't want.
like image 556
Hans En Avatar asked Aug 14 '26 20:08

Hans En


2 Answers

You can use Assume to turn tests on/off conditionally:

A set of methods useful for stating assumptions about the conditions in which a test is meaningful. A failed assumption does not mean the code is broken, but that the test provides no useful information.

like image 90
devnull Avatar answered Aug 17 '26 10:08

devnull


You can do this with JUnit Rules.

There's a whole blog post dedicated to exactly your question here, but in short, you do the following:

  1. Create a class that implements the org.junit.rules.TestRule interface. This interface contains the following method:
    Statement apply(Statement base, Description description);
    The base argument is actually your test, which you run by calling base.execute() -- well, the apply() method actually returns a Statement anonymous instance that will do that. In your anonymous Statement instance, you'll add the logic to determine whether or not the test should be run. See below for an example of a TestRule implementation that doesn't do anything except execute your test -- and yes, it's not particularly straighforward.
  2. Once you've created your TestRule implementation, then you need to add the following lines to to your JUnit Test Class:
    @Rule
    public MyTestRuleImpl conditionalTests;

    Remember, the field must be public.

And that's it. Good luck -- as I said, you may have to hack a little, but I believe there's a fair amount explained in the blog post. Otherwise, there should be other information on the internets (or in the JUnit sourc code).

Here's a quick example of a TestRule implementation that doesn't do anything.

public abstract class SimpleRule implements TestRule {
    public Statement apply(final Statement base, final Description description) {
        return new Statement() {
            public void evaluate() throws Throwable {
                try {
                    base.evaluate();
                } catch (Throwable t) { 
                    t.printStackTrace();
                }
            }
        };
    }
}
like image 31
Marco Avatar answered Aug 17 '26 09:08

Marco