2525import org .openrewrite .java .JavaVisitor ;
2626import org .openrewrite .java .MethodMatcher ;
2727import org .openrewrite .java .search .UsesMethod ;
28- import org .openrewrite .java .tree .Expression ;
29- import org .openrewrite .java .tree .J ;
30- import org .openrewrite .java .tree .Statement ;
31- import org .openrewrite .java .tree .TypeUtils ;
28+ import org .openrewrite .java .tree .*;
3229
3330import java .util .Collections ;
31+ import java .util .Objects ;
3432import java .util .Set ;
33+ import java .util .stream .Stream ;
3534
3635public class RemoveTryCatchFailBlocks extends Recipe {
3736 private static final MethodMatcher ASSERT_FAIL_NO_ARG = new MethodMatcher ("org.junit.jupiter.api.Assertions fail()" );
@@ -120,6 +119,7 @@ private static boolean isException(Expression expression) {
120119 @ NotNull
121120 private J .MethodInvocation replaceWithAssertDoesNotThrowWithoutStringExpression (ExecutionContext ctx , J .Try try_ ) {
122121 maybeAddImport ("org.junit.jupiter.api.Assertions" );
122+ maybeRemoveCatchTypes (try_ );
123123 return JavaTemplate .builder ("Assertions.assertDoesNotThrow(() -> #{any()})" )
124124 .contextSensitive ()
125125 .imports ("org.junit.jupiter.api.Assertions" )
@@ -128,10 +128,22 @@ private J.MethodInvocation replaceWithAssertDoesNotThrowWithoutStringExpression(
128128 .apply (getCursor (), try_ .getCoordinates ().replace (), try_ .getBody ());
129129 }
130130
131+ private void maybeRemoveCatchTypes (J .Try try_ ) {
132+ JavaType catchType = try_ .getCatches ().get (0 ).getParameter ().getTree ().getType ();
133+ if (catchType != null ) {
134+ Stream .of (catchType )
135+ .flatMap (t -> t instanceof JavaType .MultiCatch ? ((JavaType .MultiCatch ) t ).getThrowableTypes ().stream () : Stream .of (t ))
136+ .map (TypeUtils ::asFullyQualified )
137+ .filter (Objects ::nonNull )
138+ .forEach (t -> maybeRemoveImport (t .getFullyQualifiedName ()));
139+ }
140+ }
141+
131142 @ NotNull
132143 private J .MethodInvocation replaceWithAssertDoesNotThrowWithStringExpression (ExecutionContext ctx , J .Try try_ , Expression failCallArgument ) {
133144 // Retain the fail(String) call argument
134145 maybeAddImport ("org.junit.jupiter.api.Assertions" );
146+ maybeRemoveCatchTypes (try_ );
135147 return JavaTemplate .builder ("Assertions.assertDoesNotThrow(() -> #{any()}, #{any(String)})" )
136148 .contextSensitive ()
137149 .imports ("org.junit.jupiter.api.Assertions" )
0 commit comments