From 7546af515ad2da5a06b852e7e06995b8f9088d08 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Fri, 20 Mar 2026 20:21:20 +0100 Subject: [PATCH] Fix AssertThrowsOnLastStatement crash on TypeCast arguments Add `J.TypeCast` to the early-return filter in `extractExpressionArguments` so cast expressions like `(Object[]) null` are left in place rather than being extracted into variable declarations, which fails for array cast types. Fixes https://github.com/openrewrite/rewrite/issues/7082 --- .../junit5/AssertThrowsOnLastStatement.java | 2 +- .../AssertThrowsOnLastStatementTest.java | 43 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatement.java b/src/main/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatement.java index dd024e450..b47236c90 100644 --- a/src/main/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatement.java +++ b/src/main/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatement.java @@ -145,7 +145,7 @@ private Statement extractExpressionArguments(Statement lambdaStatement, List generatedVariableSuffixes = new HashMap<>(); return mi.withArguments(ListUtils.map(mi.getArguments(), e -> { - if (e instanceof J.Identifier || e instanceof J.Literal || e instanceof J.Empty || e instanceof J.Lambda) { + if (e instanceof J.Identifier || e instanceof J.Literal || e instanceof J.Empty || e instanceof J.Lambda || e instanceof J.TypeCast) { return e; } diff --git a/src/test/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatementTest.java b/src/test/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatementTest.java index 546fc7bce..6e7cdcfb9 100644 --- a/src/test/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatementTest.java +++ b/src/test/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatementTest.java @@ -897,4 +897,47 @@ void testThing(Map map, List list, Set set) {} ) ); } + + @Issue("https://github.com/openrewrite/rewrite/issues/7082") + @Test + void lastStatementWithTypeCastArgument() { + rewriteRun( + //language=java + java( + """ + import org.junit.jupiter.api.Test; + + import static org.junit.jupiter.api.Assertions.assertThrows; + + class MyTest { + + @Test + void test() throws Exception { + assertThrows(AssertionError.class, () -> { + java.lang.reflect.Constructor constructor = MyTest.class.getDeclaredConstructor(); + constructor.setAccessible(true); + constructor.newInstance((Object[]) null); + }); + } + } + """, + """ + import org.junit.jupiter.api.Test; + + import static org.junit.jupiter.api.Assertions.assertThrows; + + class MyTest { + + @Test + void test() throws Exception { + java.lang.reflect.Constructor constructor = MyTest.class.getDeclaredConstructor(); + constructor.setAccessible(true); + assertThrows(AssertionError.class, () -> + constructor.newInstance((Object[]) null)); + } + } + """ + ) + ); + } }