How to run entire JUnit Test Suite from within code

前端 未结 3 376
北荒
北荒 2021-01-13 18:19

In eclipse, with JUnit 4, you can right click a project or package and click Run as JUnit Test, and it will run all the JUnit tests within that grouping. Is there a way to d

相关标签:
3条回答
  • 2021-01-13 18:39

    You can use packages in junit such as JUnitCore like this:

    public static void main(String[] args){
        List tests = new ArrayList();
        tests.add(TestOne.class);
        tests.add(TestTwo.class);
    
        for (Class test : tests){
            runTests(test);
        }
    }
    
    private static void runTests(Class test){
        Result result = JUnitCore.runClasses(test);
        for (Failure failure : result.getFailures()){
            System.out.println(failure.toString());
        }
    }
    
    0 讨论(0)
  • 2021-01-13 18:46

    JUnit provides the test Suite. Give that a try.

    [...]
    public class TestCaseA {
        @Test
        public void testA1() {
            // omitted
        }
    }
    
    [...]
    public class TestCaseB {
        @Test
        public void testB1() {
            // omitted
      }
    }
    
    [...]
    @RunWith(value=Suite.class)
    @SuiteClasses(value = {TestCaseA.class})
    public class TestSuiteA {
    }
    
    [...]
    @RunWith(value=Suite.class)
    @SuiteClasses(value = {TestCaseB.class})
    public class TestSuiteB {
    }
    
    [...]
    @RunWith(value = Suite.class )
    @SuiteClasses(value = {TestSuiteA.class, TestSuiteB.class})
    public class MasterTestSuite{
    }
    
    0 讨论(0)
  • 2021-01-13 19:01

    Use JUnit Suite:

    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;
    
    @RunWith(Suite.class)
    // Put your Test Case Class here
    @Suite.SuiteClasses({
        JunitTest1.class,
        JunitTest2.class,
        JunitTest3.class
    })
    public class JunitTestSuite {}
    

    Then create a main method to run it.

    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    
    public class JunitTestSuiteRunner {
    
    public static void main(String[] args) {
    
        Result result = JUnitCore.runClasses(JunitTestSuite.class);
        for (Failure fail : result.getFailures()) {
            System.out.println(fail.toString());
        }
        if (result.wasSuccessful()) {
            System.out.println("All tests finished successfully...");
        }
    }}
    
    0 讨论(0)
提交回复
热议问题