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 2481d56bf..0b8bd18e4 100644 --- a/src/main/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatement.java +++ b/src/main/java/org/openrewrite/java/testing/junit5/AssertThrowsOnLastStatement.java @@ -25,6 +25,8 @@ import org.openrewrite.java.VariableNameUtils; import org.openrewrite.java.search.UsesMethod; import org.openrewrite.java.tree.*; +import org.openrewrite.kotlin.KotlinTemplate; +import org.openrewrite.kotlin.tree.K; import org.openrewrite.staticanalysis.LambdaBlockToExpression; import java.util.*; @@ -52,6 +54,13 @@ public TreeVisitor getVisitor() { MethodMatcher assertThrowsMatcher = new MethodMatcher( "org.junit.jupiter.api.Assertions assertThrows(java.lang.Class, org.junit.jupiter.api.function.Executable, ..)"); return Preconditions.check(new UsesMethod<>(assertThrowsMatcher), new JavaIsoVisitor() { + @Override + public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) { + // Only Java and Kotlin are supported, as the extracted variable declaration is rendered per language + return (sourceFile instanceof J.CompilationUnit || sourceFile instanceof K.CompilationUnit) && + super.isAcceptable(sourceFile, ctx); + } + @Override public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl, ExecutionContext ctx) { J.MethodDeclaration m = super.visitMethodDeclaration(methodDecl, ctx); @@ -142,6 +151,7 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl private Statement extractExpressionArguments(J.Block body, Statement lambdaStatement, List precedingVars, Space varPrefix) { if (lambdaStatement instanceof J.MethodInvocation) { + boolean kotlin = getCursor().firstEnclosing(K.CompilationUnit.class) != null; J.MethodInvocation mi = (J.MethodInvocation) lambdaStatement; Map generatedVariableSuffixes = new HashMap<>(); return mi.withArguments(ListUtils.map(mi.getArguments(), e -> { @@ -149,6 +159,22 @@ private Statement extractExpressionArguments(J.Block body, Statement lambdaState return e; } + String variableName = getVariableName(e, generatedVariableSuffixes); + + // Kotlin infers the type; add `val name = expr` as a statement on the method body, since replacing + // the expression in place would wrap the template as `var o =