How do I programmatically run all the JUnit tests in my Java application?

后端 未结 6 1948
逝去的感伤
逝去的感伤 2021-02-02 18:13

From Eclipse I can easily run all the JUnit tests in my application.

I would like to be able to run the tests on target systems from the application jar, without Eclipse

6条回答
  •  广开言路
    2021-02-02 19:09

    I ran into a minor problem with my last solution. If I ran "all tests" from Eclipse they ran twice because they ran the individual tests AND the suite. I could have worked around that, but then I realized there was a simpler solution:

    package suneido;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.jar.JarEntry;
    import java.util.jar.JarFile;
    
    public class RunAllTests {
    
        public static void run(String jarfile) {
            String[] tests = findTests(jarfile);
            org.junit.runner.JUnitCore.main(tests);
        }
    
        private static String[] findTests(String jarfile) {
            ArrayList tests = new ArrayList();
            try {
                JarFile jf = new JarFile(jarfile);
                for (Enumeration e = jf.entries(); e.hasMoreElements();) {
                    String name = e.nextElement().getName();
                    if (name.startsWith("suneido/") && name.endsWith("Test.class")
                            && !name.contains("$"))
                        tests.add(name.replaceAll("/", ".")
                                .substring(0, name.length() - 6));
                }
                jf.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return tests.toArray(new String[0]);
        }
    
        public static void main(String[] args) {
            run("jsuneido.jar");
        }
    
    }
    

提交回复
热议问题