Sample Program for junit-4.12.jar


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



JUnit is a simple framework to write repeatable tests for Java applications. In order to use junit-4.12.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 sample program,, does the following:

  • It uses @Test annotation to identify a test method.
  • It uses static 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-4.12.jar

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


Run org.junit.runner.JUnitCore in junit-4.12.jar

What Is junit-4.12.jar

Download and Install JUnit (Java Unit) Testing

⇑⇑ FAQ for JUnit (Java Unit) Testing

2016-02-24, 2448🔥, 0💬