How can I automatically skip some conditional JUnit tests?

I would like a simple way to assign a priority value to my JUnit tests, so that I can say "run only tests with priority 1", "run priority 1, 2, and 3 tests", etc. I know that I can just include a string like Assume.assumeTrue("Test skipped for priority " + priority, priority <= 2); at the beginning of each test (where priority is the tests with the highest priority value that I want to run, and 2 is the priority value of this particular test), however, copying to the line at the beginning of each test does not seem to be a very good solution.

I tried to write a solution using the simple annotation found in the JUnit rule that I use:

 public class Tests { @Rule public TestRules rules = new TestRules(); @Test @Priority(2) public void test1() { // perform test } } public class TestRules extends TestWatcher { private int priority = 1; // this value is manually changed to set the priority of tests to run @Override protected void starting(Description desc) { Priority testCasePriority = desc.getAnnotation(Priority.class); Assume.assumeTrue("Test skipped for priotity " + priority, testCasePriority == null || testCasePriority.value() <= priority); } } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Priority { public int value() default 0; } 

While this works (the correct tests appear to be skipped in the Eclipse JUnit view), the tests are still running, that is, the test1() code is still running.

Does anyone know how I can get Assume in my rule to skip a test?

+5
source share
1 answer

The exception TestWatcher.starting by TestWatcher.starting is ignored and returned at the end of the test.

You should implement TestRule instead of TestWatcher :

 public class TestRules implements TestRule { private int priority = 1; // this value is manually changed to set the priority of tests to run public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { Priority testCasePriority = desc.getAnnotation(Priority.class); Assume.assumeTrue("Test skipped for priotity " + priority, testCasePriority == null || testCasePriority.value() <= priority); base.evaluate(); } }; } } 
+3
source

Source: https://habr.com/ru/post/1243122/


All Articles