Skip to content

Commit d067547

Browse files
authored
ExpectedExceptionToAssertThrows should not wrap single statement (#555)
1 parent c2e4fba commit d067547

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

src/main/java/org/openrewrite/java/testing/junit5/ExpectedExceptionToAssertThrows.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,11 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl
160160
Object expectedExceptionParam = (expectMethodInvocation == null || isExpectArgAMatcher) ?
161161
"Exception.class" : expectMethodInvocation.getArguments().get(0);
162162

163-
String templateString = expectedExceptionParam instanceof String ? "#{}assertThrows(#{}, () -> #{});" : "#{}assertThrows(#{any()}, () -> #{});";
163+
String templateString = expectedExceptionParam instanceof String ? "#{}assertThrows(#{}, () -> #{any()});" : "#{}assertThrows(#{any()}, () -> #{any()});";
164164

165+
Statement statement = bodyWithoutExpectedExceptionCalls.getStatements().size() == 1 &&
166+
!(bodyWithoutExpectedExceptionCalls.getStatements().get(0) instanceof J.Throw) ?
167+
bodyWithoutExpectedExceptionCalls.getStatements().get(0) : bodyWithoutExpectedExceptionCalls;
165168
m = JavaTemplate.builder(templateString)
166169
.contextSensitive()
167170
.javaParser(javaParser(ctx))
@@ -172,7 +175,7 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl
172175
m.getCoordinates().replaceBody(),
173176
exceptionDeclParam,
174177
expectedExceptionParam,
175-
bodyWithoutExpectedExceptionCalls
178+
statement
176179
);
177180

178181
maybeAddImport("org.junit.jupiter.api.Assertions", "assertThrows");

src/test/java/org/openrewrite/java/testing/junit5/ExpectedExceptionToAssertThrowsTest.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
import static org.openrewrite.java.Assertions.java;
2727

28+
@SuppressWarnings({"deprecation", "JUnitMalformedDeclaration", "JUnit3StyleTestMethodInJUnit4Class", "Convert2MethodRef"})
2829
class ExpectedExceptionToAssertThrowsTest implements RewriteTest {
2930

3031
@Override
@@ -105,9 +106,7 @@ class MyTest {
105106
106107
@Test
107108
public void testEmptyPath() {
108-
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
109-
foo();
110-
});
109+
Throwable exception = assertThrows(IllegalArgumentException.class, () -> foo());
111110
assertTrue(exception.getMessage().contains("Invalid location: gs://"));
112111
}
113112
void foo() {

0 commit comments

Comments
 (0)