assertThrows
A method that rejects bad input is as much a part of its contract as a method that returns a value. The test for the rejection has to call the code and expect the throw, not let the exception escape and turn the test red. JUnit does that with assertThrows, which takes the expected type and a lambda that runs the code. The article Exceptions in tests covers the same assertion with a shorter example.
A parser that throws
Parser.java turns text into an integer and wraps the JDK parser. A good input returns a number; a bad one throws IllegalArgumentException with its own message and the original NumberFormatException as the cause.
public class Parser {
static int parse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException error) {
throw new IllegalArgumentException("not a number: " + text, error);
}
}
}
assertThrows
assertThrows(IllegalArgumentException.class, () -> Parser.parse("abc")) runs the lambda and expects it to throw the named class or a subclass. If the lambda returns normally, the test fails with Expected ... to be thrown, but nothing was thrown. If it throws another type, the test fails and the report shows that type.
The lambda form matters: the call must be inside the lambda, not evaluated as an argument before the assertion runs. Write assertThrows(X.class, () -> call()), never assertThrows(X.class, call()), which does not compile for a method that returns a value and would throw before the assertion for one that does not.
The returned exception
The assertion returns the exception it caught, so the test can inspect it. The usual checks are the message and the cause:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class ParserTest {
@Test
void parsesANumber() {
assertEquals(42, Parser.parse("42"));
}
@Test
void rejectsText() {
IllegalArgumentException error = assertThrows(
IllegalArgumentException.class,
() -> Parser.parse("abc"));
assertEquals("not a number: abc", error.getMessage());
assertEquals(NumberFormatException.class, error.getCause().getClass());
}
}
Type, message and cause
The type says what kind of failure the caller should catch, the message says what was wrong with the input, and the cause keeps the lower-level exception for a log. A test that checks only the type passes when the message is a stack trace or an empty string, so a message that the caller reads is worth an assertion of its own.
The message assertion uses assertEquals on the exact string. When the message contains a value that varies, compare a prefix with assertTrue(error.getMessage().startsWith("not a number: ")) or match a regular expression, and keep the exact text for the fixed part.
The report
javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Parser.java ParserTest.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 ✔
│ └─ ParserTest ✔
│ ├─ rejectsText() ✔
│ └─ parsesANumber() ✔
└─ JUnit Vintage ✔
Test run finished after 296 ms
[ 4 containers found ]
[ 0 containers skipped ]
[ 4 containers started ]
[ 0 containers aborted ]
[ 4 containers successful ]
[ 0 containers failed ]
[ 2 tests found ]
[ 0 tests skipped ]
[ 2 tests started ]
[ 0 tests aborted ]
[ 2 tests successful ]
[ 0 tests failed ]
Exercises
- Change the expected type to NumberFormatException.class and run. Read the failure line: which type was actually thrown?
- Call assertThrows on "42" and run. Copy the message of the red test.
- Change the wrapper to throw a checked exception. What must the test method declare, and why?
- Add an assertion on error.getCause().getMessage() and run. Does the inner message include the input?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
assertThrowstake as its second argument?Answer
An executable lambda that must throw
The lambda wraps the call so the assertion can run it and catch what it throws.
-
What does
assertThrowsreturn?Answer
The exception that was caught
The returned exception lets the test check its message and cause.
-
What happens when the lambda returns normally?
Answer
The test fails with "Expected ... to be thrown, but nothing was thrown"
The contract says the call must throw, and a normal return is the failure.
-
What does this program print?
public class Q1 { public static void main(String[] args) { System.out.println(Integer.parseInt("42") + 1); } }Answer
43
parseInt turns the text into 42, and the addition gives 43.
-
What does this program print?
public class Q2 { public static void main(String[] args) { try { Integer.parseInt("abc"); System.out.println("parsed"); } catch (NumberFormatException error) { System.out.println("bad"); } } }Answer
bad
The parse throws, the catch runs and prints bad.
-
What does this program print?
public class Q3 { public static void main(String[] args) { try { throw new IllegalArgumentException("no"); } catch (IllegalArgumentException error) { System.out.println(error.getMessage()); } } }Answer
no
The message passed to the constructor is returned by getMessage.
-
What does this program print?
public class Q4 { public static void main(String[] args) { int total = 0; for (int n = 1; n != 4; n++) { total += n; } System.out.println(total); } }Answer
6
The loop adds 1, 2 and 3, and stops at 4.
-
Why must the call be inside the lambda?
Answer
An argument is evaluated before assertThrows runs, so the exception would escape
The assertion must control when the call runs so it can catch the throw.
-
Which assertion checks the exact message of the caught exception?
Answer
assertEquals("not a number: abc", error.getMessage())
The message is a string, and assertEquals compares it exactly.
-
What does this program print?
public class Q5 { public static void main(String[] args) { String text = "abc"; System.out.println(text.length()); } }Answer
3
The string has three characters.
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