3

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.
Marco
  • 8,958
  • 1
  • 36
  • 56
Hans En
  • 906
  • 5
  • 15
  • 32
  • It looks like this [answer](http://stackoverflow.com/a/1689261/376390) might also be a solution to your question. – Marco Apr 16 '13 at 11:59

2 Answers2

3

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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
devnull
  • 118,548
  • 33
  • 236
  • 227
1

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();
                }
            }
        };
    }
}
Marco
  • 8,958
  • 1
  • 36
  • 56