running a subset of JUnit @Test methods

前端 未结 4 1811
星月不相逢
星月不相逢 2020-12-14 20:10

We\'re using JUnit 4 to test: we have classes that don\'t are a subclass of TestCase, and they have public methods annotated with @Test. We have on

4条回答
  •  轮回少年
    2020-12-14 20:40

    Create your own TestClassMethodsRunner (it's not documentated or I don't find it now).
    A TestClassMethodsRunner executes all TestCases and you can set up a filtered TestClassMethodsRunner.

    All you have to do is override the TestMethodRunner createMethodRunner(Object, Method, RunNotifier) method. This is a simple an hacky solution:

    public class FilteredTestRunner extends TestClassMethodsRunner {
    
        public FilteredTestRunner(Class aClass) {
            super(aClass);
        }
    
        @Override
        protected TestMethodRunner createMethodRunner(Object aTest, Method aMethod, RunNotifier aNotifier) {
            if (aTest.getClass().getName().contains("NOT")) {
                return new TestMethodRunner(aTest, aMethod, aNotifier, null) {
                    @Override
                    public void run() {
                        //do nothing with this test.
                    }
                };
            } else {
                return super.createMethodRunner(aTest, aMethod, aNotifier);
            }
        }
    
    }
    

    With this TestRunner, you execute all Tests that don't contain the string "NOT". Others will be ignored :) Just add the @RunWith annotation with your TestRunner class to your test.

    @RunWith(FilteredTestRunner.class)
    public class ThisTestsWillNOTBeExecuted {
       //No test is executed.
    }
    
    @RunWith(FilteredTestRunner.class)
    public class ThisTestsWillBeExecuted {
       //All tests are executed.
    }
    

    In the createMethodRunner method you can check the current test against a list of tests that must be executed or introduce new criterias.

    Good luck with this!

    Hints for a nicer solution are appreciated!

提交回复
热议问题