java data_error ai_generated true

org.opentest4j.AssertionFailedError: Expected java.lang.RuntimeException to be thrown, but java.lang.NullPointerException was thrown

ID: java/junit-assert-throws-wrong-type

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-12-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
8+ active

Root Cause

assertThrows expects a specific exception type, but a different exception is thrown.

generic

中文

assertThrows 期望特定的异常类型,但抛出了不同的异常。

Workarounds

  1. 95% success Use assertThrows with correct exception type
    assertThrows(NullPointerException.class, () -> {
        // code that throws NPE
    });
  2. 80% success Use assertThrowsAny for multiple exception types
    assertThrowsAny(RuntimeException.class, () -> {
        // code
    });

Dead Ends

Common approaches that don't work:

  1. Catching the actual exception and ignoring 60% fail

    Test passes incorrectly; real exception type mismatch is hidden.

  2. Changing expected type to Exception 50% fail

    Too broad; may hide other issues.