Run JUnit test from the command line

      No Comments on Run JUnit test from the command line

JUnit tests can be run easily from within your IDE. Every remotely up to date IDE has some built-in view that gives nice visual feedback, usually red or green indicators.

But of course it is also possible to invoke your tests from the command line. A simple example:

import org.junit.runner.JUnitCore;

public class MyClass {
    public static void main(String[] args) {
        JUnitCore.main(MyJUnitTest.class.getName());
    }
}

A very nice article on JUnit testing by Lars Vogel can be found at http://www.vogella.com/articles/JUnit/article.html. He suggests iterating through the failures of a Result class to run the tests via code, which works fine, too:

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class MyClass {
    public static void main(String[] args) {
        Result result = JUnitCore.runClasses(MyJUnitTest.class);
        for (Failure failure : result.getFailures()) {
            System.out.println(failure.toString());
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.