Command Palette

Search for a command to run...

Back to the lesson: Topic 15.5 — Unit Testing with JUnit 5
Core Java · Example 2 of 3 Java 9+

assertThrows and assertAll, written by hand

NumberFormatException passed as an IllegalArgumentException because it's a subclass, just as in JUnit. assertAll reported both failures instead of stopping at the first.

A unit test is a small program that calls your code with known inputs and checks the result automatically. JUnit 5 (the Jupiter API) finds methods marked @Test, runs each on a fresh instance of the test class, and reports passes and failures; assertions such as assertEquals and assertThrows, lifecycle methods like @BeforeEach, and @ParameterizedTest make tests short and readable.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Extend the tiny runner with an @AfterEach annotation whose methods always run, even after a failed test, and print how many methods were called in total, including setup and teardown.

02

Write the JUnit 5 test class (non-runnable here) for a Stack class: a fresh stack per test, push then pop returns the same element, pop on an empty stack throws NoSuchElementException.

03

Write a hand-made assertArrayEquals(int[] expected, int[] actual) that reports the first differing index, and use it on two arrays.

Explain it without notes

01

What is a unit test, and what makes a test good?

02

Explain the JUnit 5 lifecycle annotations and the per-method instance rule.

03

How would you test that a method throws an exception with a particular message?

04

When would you use a parameterized test, and what sources are available?

05

How does JUnit find and run your tests under the hood?

assertThrows and assertAll, written by hand Java 9+
Sign in to run this example in your browser.

Expected output

caught NumberFormatException: For input string: "abc"
assertThrows failed: expected ArithmeticException to be thrown, but nothing was thrown
assertAll failed: 2 of 3 failed: [expected: <Byron> but was: <Lovelace>, expected: <3> but was: <2>]