Skip to content

Commit

Permalink
ExpectedExceptionToAssertThrows should not wrap single statement (#555)
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek committed Jul 24, 2024
1 parent c2e4fba commit d067547
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,11 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl
Object expectedExceptionParam = (expectMethodInvocation == null || isExpectArgAMatcher) ?
"Exception.class" : expectMethodInvocation.getArguments().get(0);

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

Statement statement = bodyWithoutExpectedExceptionCalls.getStatements().size() == 1 &&
!(bodyWithoutExpectedExceptionCalls.getStatements().get(0) instanceof J.Throw) ?
bodyWithoutExpectedExceptionCalls.getStatements().get(0) : bodyWithoutExpectedExceptionCalls;
m = JavaTemplate.builder(templateString)
.contextSensitive()
.javaParser(javaParser(ctx))
Expand All @@ -172,7 +175,7 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl
m.getCoordinates().replaceBody(),
exceptionDeclParam,
expectedExceptionParam,
bodyWithoutExpectedExceptionCalls
statement
);

maybeAddImport("org.junit.jupiter.api.Assertions", "assertThrows");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

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

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

@Override
Expand Down Expand Up @@ -105,9 +106,7 @@ class MyTest {
@Test
public void testEmptyPath() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
foo();
});
Throwable exception = assertThrows(IllegalArgumentException.class, () -> foo());
assertTrue(exception.getMessage().contains("Invalid location: gs://"));
}
void foo() {
Expand Down

0 comments on commit d067547

Please sign in to comment.