The exception that never comes
The previous lessons expected an exception and got one. This one expects an exception from a call that succeeds, which is the other red report assertThrows can produce. The message is short and exact, and it sends the reader to one of two places: the test chose the wrong input, or the class no longer throws.
The test that expects too much
Parser.java is the parser from lesson 021: a number returns a number, any other text throws. ParserTest.java asks for the exception from "42", which is a number. The call returns normally, so the assertion has nothing to catch.
public class Parser {
static int parse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException error) {
throw new IllegalArgumentException("not a number: " + text, error);
}
}
}
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class ParserTest {
@Test
void rejectsANumber() {
assertThrows(IllegalArgumentException.class, () -> Parser.parse("42"));
}
}
The red 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 ✔
│ └─ rejectsANumber() ✘ Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown.
└─ JUnit Vintage ✔
Failures (1):
JUnit Jupiter:ParserTest:rejectsANumber()
MethodSource [className = 'ParserTest', methodName = 'rejectsANumber', methodParameterTypes = '']
=> org.opentest4j.AssertionFailedError: Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown.
org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:152)
org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:73)
org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:35)
org.junit.jupiter.api.Assertions.assertThrows(Assertions.java:3128)
ParserTest.rejectsANumber(ParserTest.java:8)
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 303 ms
[ 4 containers found ]
[ 0 containers skipped ]
[ 4 containers started ]
[ 0 containers aborted ]
[ 4 containers successful ]
[ 0 containers failed ]
[ 1 tests found ]
[ 0 tests skipped ]
[ 1 tests started ]
[ 0 tests aborted ]
[ 0 tests successful ]
[ 1 tests failed ]
Reading the message
Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown. names the expected type and the outcome. It is not a compile error: the lambda compiled, the call ran, and the call returned a value. The stack goes through AssertThrows.assertThrows and ends at the test line, because the failure is the assertion, not the parser.
The message does not include the value the lambda returned. That is why the test should call a method whose result is uninteresting, or assert on the result in a separate test; the assertion is about the throw, not about the number.
The fix
There are two honest fixes, and the choice depends on the contract. If the class is right and the test chose the wrong input, change "42" to "abc". If the class should reject a number, change the class so that it does; then the test is already correct and the code catches up.
The dishonest fix is to delete the assertion or to catch the exception outside it. A test that no longer expects the throw stops protecting the contract, and the report becomes green for a rule nobody checks.
Why this happens
The common cause is a test written from the desired behaviour rather than from the current one: the class is supposed to throw, but the guard is missing. That is the useful red test, and the fix belongs in the class. The second cause is a copied test with the wrong input, where the fix belongs in the test. The message is the same in both cases, which is why the person has to read the code and decide.
The assertThrows lesson shows the green version of the same assertion with a message and a cause; this page is its red mirror.
Exercises
- Change the input to "abc" and run. Confirm that the test is green and the counts show one successful test.
- Change the parser so that it throws for every input and run. Does the test pass for the right reason?
- Add a second test that asserts the returned number for "42". Which of the two tests would have caught the missing guard?
- Replace assertThrows with a plain call and run. What is the report shape now?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the message "but nothing was thrown" mean?
Answer
The lambda returned normally, so the expected exception never happened
assertThrows fails when the call returns instead of throwing the expected type.
-
Which fix belongs in the test?
Answer
Use an input that the contract says must throw
If the class is right, the test input was wrong; a broader expected type hides the rule.
-
Which fix belongs in the class?
Answer
Add the missing guard so the invalid input throws
When the red test states the intended contract, the production code is what changes.
-
What does this program print?
public class Q1 { public static void main(String[] args) { System.out.println(Integer.parseInt("42")); } }Answer
42
The text is a valid number, and println prints the integer 42.
-
What does this program print?
public class Q2 { public static void main(String[] args) { try { throw new IllegalStateException("no"); } catch (IllegalStateException error) { System.out.println("caught"); } } }Answer
caught
The catch block matches the thrown type and prints caught.
-
What does this program print?
public class Q3 { public static void main(String[] args) { String text = "abc"; System.out.println(text.length()); } }Answer
3
The string has three characters.
-
What does this program print?
public class Q4 { public static void main(String[] args) { System.out.println(42 + 1); } }Answer
43
The addition gives 43, and println prints it.
-
Why does the failure stack end at the test line rather than in the parser?
Answer
The failure is the assertion, not an exception from the parser
assertThrows builds the failure after the call returned, so the stack starts in the assertion.
-
What does this program print?
public class Q5 { public static void main(String[] args) { System.out.println("abc".length() + 1); } }Answer
4
The string has three characters, and 3 + 1 is 4.
-
Which change hides the contract instead of fixing the test?
Answer
Catching the exception outside assertThrows
A catch outside the assertion lets the call return and removes the check the test was for.
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