Running a Test Class Directly

Problem

You don’t want to invoke one of the JUnit test runners. Instead, you would like to run your test directly.

Solution

Add a main( ) method to your test case. Or, use Ant to run your tests as discussed in Chapter 3.

Discussion

Adding a main( ) method can make a class easier to run. Most IDEs allow you to click on a class and select some sort of “run” option from a popup menu, provided the class has a main( ) method. Here is a sample main( ) method for our TestGame class:

public class TestGame extends TestCase {
    ...
    public static void main(String[] args) {
               junit.textui.TestRunner.run(new TestSuite(TestGame.class));
               }
}

When executed, this method runs the test suite in text mode. Output is sent to the console.

See Also

Recipe 4.3 shows how to run unit tests. Chapter 3 shows how to run tests using Ant.

Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.