A generic stack

A type parameter is tested twice: once with a reference type that carries text and once with a wrapper type that carries a number, because the compiler erases the parameter and the runtime behaves the same. This lesson tests a small stack with strings and integers and adds the empty case, where the class has to refuse instead of returning null.

A generic stack

Stack.java keeps an ArrayList and pushes to its end. pop removes the last element, which is the top of the stack, and throws a message when there is nothing to remove.

import java.util.ArrayList; import java.util.List; public class Stack<T> { private final List<T> items = new ArrayList<>(); void push(T item) { items.add(item); } T pop() { if (items.isEmpty()) { throw new IllegalStateException("empty stack"); } return items.remove(items.size() - 1); } int size() { return items.size(); } }

Three tests

The first test checks the last-in first-out order and the size after one pop. The second uses an Integer argument, which is the same class with another type. The third expects the exception from an empty stack.

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class StackTest { @Test void popsTheLastPushed() { Stack<String> stack = new Stack<>(); stack.push("first"); stack.push("second"); assertEquals("second", stack.pop()); assertEquals(1, stack.size()); } @Test void popsIntegers() { Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(2); assertEquals(2, stack.pop()); } @Test void rejectsAnEmptyPop() { Stack<String> stack = new Stack<>(); IllegalStateException error = assertThrows(IllegalStateException.class, stack::pop); assertEquals("empty stack", error.getMessage()); } }

Two type arguments

The compiler erases T from the class file, so the two tests exercise the same bytecode with different objects. That is not a reason to test every type: a string and a number cover the paths that autoboxing and the list can take, and a third type would add a test without a new branch. When the class has a bound, such as T extends Number, the bound is worth a type of its own.

The empty stack

pop on an empty stack has three possible contracts: return null, return an Optional, or throw. This class throws, and the test pins the type and the message. A change to returning null would fail the test, which is the point: the caller must not have to guess.

The method reference stack::pop is an Executable, so it fits assertThrows without a lambda. The report names the class and the message the same way.

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Stack.java StackTest.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 ✔
│  └─ StackTest ✔
│     ├─ popsIntegers() ✔
│     ├─ rejectsAnEmptyPop() ✔
│     └─ popsTheLastPushed() ✔
└─ JUnit Vintage ✔

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

Exercises

  1. Push three items and pop them all. Write the assertions in the order the stack returns the values.
  2. Add a peek method that reads the top without removing it, and a test for it.
  3. Change the empty contract to return null and update the test. Which assertion replaces assertThrows?
  4. Make Stack accept any type and test it with a record you define in the test file.

Questions

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

  1. Which element does pop return from a stack?

    Answer

    The last one pushed

    A stack is last-in first-out, so the top is the most recent push.

  2. Why test the same class with a String and an Integer?

    Answer

    A reference type and a wrapper cover the paths the erased type can take

    The two tests exercise the same bytecode with an object and a boxed number.

  3. What does the empty-stack test pin down?

    Answer

    The exception type and the message

    The test states that an empty pop throws IllegalStateException with that message.

  4. What does this program print? public class Q1 { public static void main(String[] args) { java.util.List<String> items = new java.util.ArrayList<>(); items.add("a"); items.add("b"); System.out.println(items.remove(items.size() - 1)); } }

    Answer

    b

    remove at the last index returns the last element, b.

  5. What does this program print? public class Q2 { public static void main(String[] args) { java.util.List<Integer> items = new java.util.ArrayList<>(); items.add(1); items.add(2); System.out.println(items.size()); } }

    Answer

    2

    Two elements were added, so the size is 2.

  6. What does this program print? public class Q3 { public static void main(String[] args) { System.out.println("empty stack".length()); } }

    Answer

    11

    The phrase empty stack has eleven characters, the space included.

  7. What does this program print? public class Q4 { public static void main(String[] args) { java.util.List<String> items = new java.util.ArrayList<>(); System.out.println(items.isEmpty()); } }

    Answer

    true

    A new list has no elements, so isEmpty is true.

  8. What is type erasure?

    Answer

    The compiler removes the type parameter from the class file

    The parameter is a compile-time check; the runtime class has no T in it.

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

    Answer

    3

    The two integers are added, and println prints 3.

  10. Which assertion fits assertThrows(IllegalStateException.class, stack::pop)?

    Answer

    assertEquals("empty stack", error.getMessage())

    The assertion returns the exception, and its message is the contract the test checks.

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