Skip to content
VirtualLP Virtual Learning Platform

Practical 19: Unit Testing with JUnit (Calculator)

14 min read Topic 28 of 31 1 hands-on lab

Aim

Write a Java calculator with add, subtract, multiply and divide methods. Use JUnit to check the answers for positive numbers, negative numbers and zero. Also test division by zero and number limits.

Theory

A unit test checks one small part of a program, often one method. It gives known input and compares the answer with the expected value.

For example, add(2, 3) should return 5. Tests should also check unusual inputs, such as dividing by zero. An assertion makes each check.

checking a calculator

Before selling a calculator, the shop tests every button: 2 + 3 = 5 (normal), −1 + −2 = −3 (negative numbers), 5 × 0 = 0 (zero), and 10 ÷ 0 must show Error, not a wrong number (exception). Our JUnit tests do exactly this for the Calculator class – automatically, in a fraction of a second.

Benefit Explanation
Early defect detection Bugs are found while writing code, when they are cheapest to fix
Safe refactoring Passing tests check the cases they cover; they cannot prove all behaviour is unchanged
Living documentation Tests show how a class is meant to be used
Supports TDD (Test-Driven Development) Write a failing test → make it pass → refactor (red–green–refactor)

Characteristics of good unit tests – FIRST

Fast · Independent · Repeatable · Self-validating (pass/fail automatically) · Timely (written with the code).

Structure of a test – AAA

AAA means Arrange, Act, Assert.

AAA means Arrange, Act, Assert: prepare the data, call the method, then check its answer.

@Test
public void addTwoPositiveNumbers() {
    Calculator calc = new Calculator();     // Arrange
    int result = calc.add(2, 3);            // Act
    assertEquals(5, result);                // Assert
}

Designing test cases

Technique Calculator example
Equivalence partitioning positive, negative, zero operands
Boundary value analysis Integer.MAX_VALUE, Integer.MIN_VALUE, 0
Exception testing division by zero must throw ArithmeticException
Precision double results compared with a delta

Requirements

Eclipse, JDK (Java Development Kit) 17 and JUnit 4.13.2. The imports and annotations below use JUnit 4; JUnit 5 needs different imports and some different test syntax.

Procedure

  1. Create Java project CalculatorUnitTest and add JUnit 4 through Build Path → Add Library → JUnit.
  2. Create package vlp.calc with class Calculator (production code).
  3. Right-click Calculator → New → JUnit Test Case → name CalculatorTest, tick the methods to test → Finish.
  4. Write the tests below, then Run As → JUnit Test.
  5. (Optional) Coverage As → JUnit Test to see line/branch coverage (EclEmma).

Calculator.java

package vlp.calc;

public class Calculator {

    public int add(int a, int b) {
        return Math.addExact(a, b);          // throws ArithmeticException on overflow
    }

    public int subtract(int a, int b) {
        return Math.subtractExact(a, b);
    }

    public int multiply(int a, int b) {
        return Math.multiplyExact(a, b);
    }

    public double divide(double a, double b) {
        if (b == 0) {
            throw new ArithmeticException("Division by zero");
        }
        return a / b;
    }
}

CalculatorTest.java

package vlp.calc;

import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;

public class CalculatorTest {

    private Calculator calc;
    private static final double DELTA = 1e-9;

    @Before
    public void setUp() {
        calc = new Calculator();          // fresh object for every test (independence)
    }

    // ---------- addition ----------
    @Test
    public void addPositiveNumbers() {
        assertEquals(15, calc.add(10, 5));
    }

    @Test
    public void addNegativeNumbers() {
        assertEquals(-15, calc.add(-10, -5));
    }

    @Test
    public void addWithZero() {
        assertEquals(7, calc.add(7, 0));
    }

    @Test(expected = ArithmeticException.class)
    public void addOverflowThrows() {
        calc.add(Integer.MAX_VALUE, 1);
    }

    // ---------- subtraction ----------
    @Test
    public void subtractGivesNegativeResult() {
        assertEquals(-5, calc.subtract(5, 10));
    }

    @Test
    public void subtractSameNumbersIsZero() {
        assertEquals(0, calc.subtract(42, 42));
    }

    // ---------- multiplication ----------
    @Test
    public void multiplyPositiveNumbers() {
        assertEquals(50, calc.multiply(10, 5));
    }

    @Test
    public void multiplyByZero() {
        assertEquals(0, calc.multiply(99, 0));
    }

    @Test
    public void multiplyNegativeByPositive() {
        assertEquals(-20, calc.multiply(-4, 5));
    }

    // ---------- division ----------
    @Test
    public void divideExact() {
        assertEquals(2.0, calc.divide(10, 5), DELTA);
    }

    @Test
    public void divideWithFraction() {
        assertEquals(3.3333333333, calc.divide(10, 3), 1e-6);
    }

    @Test
    public void divideNegative() {
        assertEquals(-2.5, calc.divide(-5, 2), DELTA);
    }

    @Test
    public void divideByZeroThrowsException() {
        ArithmeticException ex = assertThrows(ArithmeticException.class, () -> calc.divide(10, 0));
        assertEquals("Division by zero", ex.getMessage());
    }
}

Parameterised version (JUnit 4)

package vlp.calc;

import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class CalculatorAddParamTest {
    private final int a, b, expected;

    public CalculatorAddParamTest(int a, int b, int expected) {
        this.a = a; this.b = b; this.expected = expected;
    }

    @Parameters(name = "{0} + {1} = {2}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
            { 1, 2, 3 }, { -1, -2, -3 }, { -5, 5, 0 }, { 0, 0, 0 }, { 1000, 2000, 3000 }
        });
    }

    @Test
    public void add() {
        assertEquals(expected, new Calculator().add(a, b));
    }
}

Virtual lab · Testing Tools · 30 min

Unit testing a Calculator with JUnit 4

Put JUnit 4 on the build path, run a real test class in Eclipse, watch the red bar on a wrong expectation, complete the division tests (delta comparison and expected exceptions) and add a parameterised test.

Open lab

Output

Example output for the settings in this lesson:

JUnit view
Runs: 13/13   Errors: 0   Failures: 0
✔ CalculatorTest (0.041 s)
   ✔ addPositiveNumbers   ✔ addNegativeNumbers   ✔ addWithZero   ✔ addOverflowThrows
   ✔ subtractGivesNegativeResult   ✔ subtractSameNumbersIsZero
   ✔ multiplyPositiveNumbers   ✔ multiplyByZero   ✔ multiplyNegativeByPositive
   ✔ divideExact   ✔ divideWithFraction   ✔ divideNegative   ✔ divideByZeroThrowsException

CalculatorAddParamTest: Runs 5/5 – [1 + 2 = 3] [-1 + -2 = -3] [-5 + 5 = 0] [0 + 0 = 0] [1000 + 2000 = 3000]

Observations

  • Floating-point results are compared with a delta because 10/3 cannot be represented exactly.
  • Exception behaviour is checked with @Test(expected = …) and assertThrows.
  • A deliberately wrong expectation (for example assertEquals(16, calc.add(10, 5))) produces java.lang.AssertionError: expected:<16> but was:<15> – a failure, shown in the Failure Trace.

Conclusion

Run the calculator tests and inspect each result. Check both normal answers and expected errors. Run the tests again after a code change to check that earlier behaviour still works.

Viva questions

  1. What is unit testing? Who performs it? Testing the smallest parts (methods, classes) in isolation – usually by developers.
  2. Explain the AAA pattern and FIRST principles. Arrange → Act → Assert; tests should be Fast, Independent, Repeatable, Self-validating and Timely.
  3. Why is a delta used in assertEquals for doubles? Decimal results such as 10/3 are not exact in binary, so we allow a tiny tolerance.
  4. How do you test that a method throws an exception in JUnit 4 and JUnit 5? JUnit 4: @Test(expected = ArithmeticException.class); JUnit 5 (and 4.13): assertThrows(ArithmeticException.class, () -> calc.divide(1, 0)).
  5. What is a parameterised test? One test method run many times with different input/expected values.
  6. What is TDD (red–green–refactor)? Write a failing test (red), write just enough code to pass (green), then clean up the code (refactor).
  7. What is code coverage? Which Eclipse tool measures it? The percentage of code lines/branches run by the tests; measured with EclEmma (JaCoCo) – Coverage As → JUnit Test.

Practise this topic

Hands-on virtual lab

Apply what you just read in a realistic, guided simulation. Free with a verified account.

Create a free account to track your progress and unlock virtual labs.