Java JUnit Tutorial - JUnit TestResult








TestResult collects the results of executing a test case.

TestResult Class

Following is the declaration for org.junit.TestResult class:

public class TestResult extends Object

A failure is anticipated and checked for with assertions.

Errors are unanticipated problems such as ArrayIndexOutOfBoundsException.

The following list has some frequently used methods from TestResult class.

  • void addError(Test test, Throwable t)
    Adds an error to the list of errors.
  • void addFailure(Test test, AssertionFailedError t)
    Adds a failure to the list of failures.
  • void endTest(Test test)
    Informs the result that a test was completed.
  • int errorCount()
    Gets the number of detected errors.
  • Enumeration<TestFailure> errors()
    Returns an Enumeration for the errors.
  • int failureCount()
    Gets the number of detected failures.
  • void run(TestCase test)
    Runs a TestCase.
  • int int runCount()
    Gets the number of run tests.
  • void startTest(Test test)
    Informs the result that a test will be started.
  • void stop()
    Marks that the test run should stop.




Example

The following code shows how to use TestResult.

import org.junit.Test;
import junit.framework.AssertionFailedError;
import junit.framework.TestResult;
/*from w  ww. jav  a2  s .c o  m*/
public class TestJunit extends TestResult {
   // add the error
   public synchronized void addError(Test test, Throwable t) {
      super.addError((junit.framework.Test) test, t);
   }
   // add the failure
   public synchronized void addFailure(Test test, AssertionFailedError t) {
      super.addFailure((junit.framework.Test) test, t);
   }
   @Test
   public void testAdd() {
   // add any test
   }   
   // Marks that the test run should stop.
   public synchronized void stop() {
      System.out.println("stop the test here");
   }
}




Run

Here is the code of how to run the TestResult above.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
/*from   www .j  a va  2  s  .  c  o m*/
public class Main {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

The code above generates the following result.