Sample Program for junit-3.8.1.jar


How to write a Sample program to use junit-3.8.1.jar?



JUnit is a simple framework to write repeatable tests for Java applications. In order to use junit-3.8.1.jar, we need to write a simple Java application,

// Copyright (c) 2015
public class Calculator {
  public int evaluate(String expression) {
    int sum = 0;
    for (String summand: expression.split("\+"))
      sum += Float.valueOf(summand);
    return sum;

This sample Java program is simple. But it does have some issues:

  • It does not support substraction well.
  • It does not support numbers with fractions well.

Let's write JUnit test program, CalculatorTest.jar, to show those issues:

// Copyright (c) 2015
import junit.framework.TestCase;
public class CalculatorTest extends TestCase {
  public void testAddition() {
    Calculator calculator = new Calculator();
    int sum = calculator.evaluate("1+2+3");
    assertEquals(6, sum);
  public void testFraction() {
    Calculator calculator = new Calculator();
    int sum = calculator.evaluate("2.4+2.6");
    assertEquals(5, sum);
  public void testSubtraction() {
    Calculator calculator = new Calculator();
    int sum = calculator.evaluate("10-1");
    assertEquals(9, sum);

This JUnit test program does the following:

  • It extends junit.framework.TestCase to support testXXX() methods.
  • It uses JUnit method assertEquals() to perform an equal assertion.

Of course, you need to compile them with JDK to make them ready to run:

\fyicenter>java -version
java version "1.8.0_45"


\fyicenter>javac -cp .;\local\lib\junit-3.8.1.jar

Note that you need to provided junit-3.8.1.jar in the classpath to compile


Run Sample with junit-3.8.1.jar in Text Mode

What Is junit-3.8.1.jar

Older Versions of JUnit

⇑⇑ FAQ for JUnit (Java Unit) Testing

2016-03-09, 3439🔥, 0💬