A calculator end to end

The parts of the course so far have each shown one idea. This lesson puts four of them in one class: a value test, an arithmetic test, an integer-division test and an exception test. One expected value is wrong, so the first run is red; one character fixes it and the second run is green.

The calculator

Calculator.java has three operations. divide checks the divisor and throws a message of its own rather than letting the JVM's message escape.

public class Calculator { static int add(int a, int b) { return a + b; } static int subtract(int a, int b) { return a - b; } static int divide(int a, int b) { if (b == 0) { throw new ArithmeticException("division by zero"); } return a / b; } }

Four tests

The tests cover the three operations and the guard. The subtraction test is wrong on purpose: it expects 4 from 5 minus 2. The other three are right.

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class CalculatorTest { @Test void adds() { assertEquals(5, Calculator.add(2, 3)); } @Test void subtracts() { assertEquals(4, Calculator.subtract(5, 2)); } @Test void divides() { assertEquals(3, Calculator.divide(7, 2)); } @Test void rejectsDivisionByZero() { ArithmeticException error = assertThrows( ArithmeticException.class, () -> Calculator.divide(1, 0)); assertEquals("division by zero", error.getMessage()); } }

The red run

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Calculator.java CalculatorTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ CalculatorTest ✔
│     ├─ rejectsDivisionByZero() ✔
│     ├─ adds() ✔
│     ├─ subtracts() ✘ expected: <4> but was: <3>
│     └─ divides() ✔
└─ JUnit Vintage ✔

Failures (1):
  JUnit Jupiter:CalculatorTest:subtracts()
    MethodSource [className = 'CalculatorTest', methodName = 'subtracts', methodParameterTypes = '']
    => org.opentest4j.AssertionFailedError: expected: <4> but was: <3>
       org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:151)
       org.junit.jupiter.api.AssertionFailureBuilder.buildAndThrow(AssertionFailureBuilder.java:132)
       org.junit.jupiter.api.AssertEquals.failNotEqual(AssertEquals.java:197)
       org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:150)
       org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:145)
       org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:531)
       CalculatorTest.subtracts(CalculatorTest.java:14)
       java.base/java.lang.reflect.Method.invoke(Method.java:580)
       java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
       java.base/java.util.ArrayList.forEach(ArrayList.java:1596)

Test run finished after 369 ms
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         4 tests found           ]
[         0 tests skipped         ]
[         4 tests started         ]
[         0 tests aborted         ]
[         3 tests successful      ]
[         1 tests failed          ]

The fix

The calculator is right and the test is wrong: five minus two is three. Change the expected value to 3. The fixed test class is the whole file, not a fragment:

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class CalculatorTest { @Test void adds() { assertEquals(5, Calculator.add(2, 3)); } @Test void subtracts() { assertEquals(3, Calculator.subtract(5, 2)); } @Test void divides() { assertEquals(3, Calculator.divide(7, 2)); } @Test void rejectsDivisionByZero() { ArithmeticException error = assertThrows( ArithmeticException.class, () -> Calculator.divide(1, 0)); assertEquals("division by zero", error.getMessage()); } }

The green run

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Calculator.java CalculatorTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ CalculatorTest ✔
│     ├─ rejectsDivisionByZero() ✔
│     ├─ adds() ✔
│     ├─ subtracts() ✔
│     └─ divides() ✔
└─ JUnit Vintage ✔

Test run finished after 674 ms
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         4 tests found           ]
[         0 tests skipped         ]
[         4 tests started         ]
[         0 tests aborted         ]
[         4 tests successful      ]
[         0 tests failed          ]

What the lesson shows

Four tests, one failure, one edit, four successes. The exception test stayed green through the change, which is the point of keeping it in the same class: a fix to one operation should not disturb the guard on another. The parts that follow build larger classes, but the shape stays this one.

Exercises

  1. Add a test for division with a negative divisor and predict the result before you run it.
  2. Break the guard in divide and run. Which test fails, and what is the message?
  3. Change divide to return a double and update the tests. Which assertions need a delta?
  4. Add a test for add(Integer.MAX_VALUE, 1) and explain the overflow without changing the class.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why is only one test red in the first run?

    Answer

    One expected value is wrong; the code is right

    The subtraction expected 4 and the method returned 3; the other three expectations match.

  2. What should the subtraction test expect for 5 - 2?

    Answer

    3

    Five minus two is three.

  3. What does the guard in divide protect?

    Answer

    A division by zero, which would throw an ArithmeticException

    Integer division by zero has no result, so the method throws a message of its own.

  4. What does this program print? public class Q1 { public static void main(String[] args) { System.out.println(5 - 2); } }

    Answer

    3

    The subtraction gives 3, and println prints it.

  5. What does this program print? public class Q2 { public static void main(String[] args) { System.out.println(7 / 2); } }

    Answer

    3

    Integer division truncates, so 7 divided by 2 is 3.

  6. What does this program print? public class Q3 { public static void main(String[] args) { System.out.println(2 + 3); } }

    Answer

    5

    The two integers are added, and println prints 5.

  7. What does this program print? public class Q4 { public static void main(String[] args) { try { System.out.println(1 / 0); } catch (ArithmeticException error) { System.out.println("zero"); } } }

    Answer

    zero

    The division throws, the catch matches, and zero is printed.

  8. Why keep the exception test in the same class as the value tests?

    Answer

    A fix to one operation should not disturb the guard on another

    The class tests one unit, and every rule of that unit belongs with it.

  9. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println(10 % 3); } }

    Answer

    1

    Ten divided by three leaves a remainder of 1.

  10. What does a green run return to the shell?

    Answer

    0

    The launcher returns 0 when no test failed.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev