Chapter 10. Testing Your Code with JUnit

JUnit 3.8 and JUnit 4

JUnit was a groundbreaking piece of software in its day, and there are many, many useful JUnit extensions that help with unit testing in specialized areas and that still rely on the JUnit 3.x approach. We will look at a few of them later on in the book. This section is a brief refresher on JUnit 3.8, for future reference and to better understand the changes brought by newer frameworks such as JUnit 4 and TestNG (Chapter 20).

In JUnit 3, you write unit tests in special Java classes, called test cases. All JUnit 3 test cases must extend the TestCase class. You write unit tests as methods of these classes, following a special naming convention: test methods must return void, take no parameters, and start with the word “test.” Your test classes usually also follow a particular naming convention, such as ending with the word Test.

Here is a simple Unit 3.8 test class that tests a class that calculates GST (“Goods and Services Tax,” also known as a “Value Added Tax” in some countries). Suppose that the standard GST rate is 12.5 percent. Our unit test class might look like this:

public class PriceCalculatorTest extends TestCase {

    public void testCalculateGST() {
       calculator = new PriceCalculator();
       double amountWithGst = calculator.calculatePriceWithGST(100.00);
       assertEquals("Standard GST is 12.5%", 112.50, amountWithGst, 0.0);
    }
}

The TestCase base class comes with a large number of assert methods: assertEquals(), assertTrue()

Get Java Power Tools 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.