Getting Started
Problem
You want to write unit tests with JUnit.
Solution
Create a subclass of junit.framework.TestCase.
Each unit test is represented by a testXXX( )
method within the
TestCase
subclass.
Discussion
Example 4-1 shows an extremely simple test case. A
test
case is a subclass of
TestCase and contains a collection of unit tests.
Instances of TestCase are sometimes referred to as
test fixtures, although
we prefer to say “test case” since
that matches the class name. Each unit test is a public, no-argument
method beginning with “test”. If
you do not follow this naming convention, JUnit will not be able to
locate your test methods automatically. Instead, you would have to
write a suite( ) method and construct instances of
your test case, passing the test method name
to the constructor.
Example 4-1. Simple test case
package com.oreilly.javaxp.common;
import junit.framework.TestCase;
/**
* Sample unit tests for the {@link Person} class.
*/
public class TestPerson extends TestCase {
/**
* This constructor is only required in JUnit 3.7 and earlier.
* @param testMethodName the name of the test method to execute.
*/
public TestPerson(String testMethodName) {
super(testMethodName);
}
/**
* A unit test to verify the name is formatted correctly.
*/
public void testGetFullName( ) {
Person p = new Person("Aidan", "Burke");
assertEquals("Aidan Burke", p.getFullName( )); } /** * A unit test to verify that nulls are handled properly. */ public void testNullsInName( ) { Person p = new Person(null, ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access