Java JUnit Tutorial - JUnit TestCase

TestCase defines a test case with the fixture to run multiple tests.

TestCase Class

org.junit.TestCase class id declared as follows.

public abstract class TestCase extends Assert implements Test

A test case defines the fixture to run multiple tests.

The follow list has some frequently used methods from TestCase class.

  • int countTestCases()
    Counts the number of test cases.
  • TestResult createResult()
    Creates a default TestResult object.
  • String getName()
    Gets the name of a TestCase.
  • TestResult run()
    A convenience method to run this test.
  • void run(TestResult result)
    Runs the test case and collects the results in TestResult.
  • void setName(String name)
    Sets the name of a TestCase.
  • void setUp()
    Sets up the fixture, for example, open a database connection.
  • void tearDown()
    Tears down the fixture, for example, close a database connection.
  • String toString()
    Returns a string representation of the test case.


The following code shows how to use TestCase

import junit.framework.TestCase;
//from w w  w  . ja va2 s.c o m
import org.junit.Before;
import org.junit.Test;
public class TestJunit extends TestCase  {
   protected double fValue1;
   protected double fValue2;
   public void setUp() {
      fValue1= 2.0;
      fValue2= 3.0;
   public void testAdd() {
      //count the number of test cases
      System.out.println("No of Test Case = "+ this.countTestCases());
      //test getName 
      String name= this.getName();
      System.out.println("Test Case Name = "+ name);

      //test setName
      String newName= this.getName();
      System.out.println("Updated Test Case Name = "+ newName);
      assertEquals(5.0, fValue1+fValue2);
   //tearDown used to close the connection or clean up activities
   public void tearDown(  ) {
     System.out.println("clean up.");

Run Test Cases

Here is the code to run the Test case defined above.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
// w  ww  . j av a  2s. co  m
public class Main {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {

The code above generates the following result.