java.lang.AssertionError: 期望为 null,但实际为:<某个值>
java.lang.AssertionError: expected null, but was: <some value>
ID: java/assertion-error-expected-not-null
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| JUnit 4.13 | active | — | — | — |
| JUnit 5.10 | active | — | — | — |
| Java 8+ | active | — | — | — |
根因分析
代码中的断言(通常来自 JUnit 等测试框架或显式的 assert 语句)失败,因为期望为 null 的值实际不为 null,表明空值处理存在逻辑错误。
English
An assertion in the code (typically from a test framework like JUnit or an explicit assert statement) failed because a value that was expected to be null was not null, indicating a logic error in null handling.
官方文档
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/AssertionError.html解决方案
-
Trace back to the source of the non-null value. For example, if a method is expected to return null but returns a value, add debug logging: System.out.println("Value: " + value); and check the method's logic. -
Use a conditional breakpoint in the IDE (e.g., IntelliJ IDEA) set on the assertion line to inspect variables when the assertion fails.
-
If using JUnit, replace assertNull with assertNotNull if the expectation is incorrect, or use assertNull(obj, "message") to add a descriptive message for debugging.
无效尝试
常见但无效的做法:
-
Remove the assertion entirely from the code
95% 失败
This suppresses the symptom but does not fix the underlying null-handling bug; the logic may still produce incorrect results.
-
Change the expected value in the assertion to match the actual value
90% 失败
This bypasses the validation and may hide a real bug where null was expected but a non-null value indicates an error in the system.
-
Add a try-catch block to swallow the AssertionError
85% 失败
AssertionErrors are not meant to be caught; swallowing them violates the intent of the assertion and can lead to silent failures.