Interview Questions

Do You Need to Write a main() Method in a JUnit Test Case Class?

JUnit Questions and Answers


(Continued from previous question...)

Do You Need to Write a main() Method in a JUnit Test Case Class?

The right answer to this question is "No". But many developers do write a main() method in a JUnit test case class to call a JUnit test runner to run all tests defined in this class. This is not recommended, because you can always call a JUnit runner to run a test case class as a system command.

If you want to know how to call a JUnit runner in a main() method, you can this code included in the sample test case class listed in the previous question. This code is provided by Varun Chopra and valid for JUnit 3.8.

public static void main(String[] args) {
  junit.textui.TestRunner.run(DirListerTest.class);
}

junit.textui.TestRunner.run() method takes test class name as argument. Using reflection, this method finds all class methods whose name starts with test. So it will find following 3 methods:

  testCreateLogFile()
  testExists()
  testGetChildList()

It will execute each of the 3 methods in unpredictable sequence (hence test case methods should be independent of each other) and give the result in console. Result will be something like this:

Time: 0.016
OK (3 tests)

In case you want to see the output in a GUI, you just need to replace statement in main method with following:

    junit.swingui.TestRunner.run(DirListerTest.class);

This will open up a nice swing based UI, which will show a green progress bar to show the status.

(Continued on next question...)

Other Interview Questions