Skip to content

Commit 4abcea4

Browse files
committed
Fix TemporaryFolderToTempDir for chained newFolder() calls
The recipe was not properly traversing the containment hierarchy formed by chained method invocations and thus didn't transform `newFolder()` invocations when they were chained. Fixes: #311
1 parent af8172b commit 4abcea4

File tree

2 files changed

+59
-3
lines changed

2 files changed

+59
-3
lines changed

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

+3-3
Original file line numberDiff line numberDiff line change
@@ -238,10 +238,10 @@ public TranslateNewFolderMethodInvocation(J.MethodInvocation method, JavaType.Me
238238

239239
@Override
240240
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
241-
if (!method.isScope(methodScope)) {
242-
return method;
243-
}
244241
J.MethodInvocation mi = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
242+
if (!mi.isScope(methodScope)) {
243+
return mi;
244+
}
245245
if (mi.getSelect() != null) {
246246
J tempDir = mi.getSelect().withType(JavaType.ShallowClass.build("java.io.File"));
247247
List<Expression> args = mi.getArguments().stream().filter(arg -> !(arg instanceof J.Empty)).collect(Collectors.toList());

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

+56
Original file line numberDiff line numberDiff line change
@@ -613,4 +613,60 @@ void doSomething(TemporaryFolder tempFolder) {
613613
)
614614
);
615615
}
616+
617+
@Test
618+
@Issue("https://github.com/openrewrite/rewrite-testing-frameworks/issues/311")
619+
void newFolderChainedCall() {
620+
//language=java
621+
rewriteRun(
622+
java(
623+
"""
624+
import java.io.File;
625+
import java.io.IOException;
626+
import java.nio.file.Path;
627+
import org.junit.Rule;
628+
import org.junit.Test;
629+
import org.junit.rules.TemporaryFolder;
630+
631+
public class TempDirTest
632+
{
633+
@Rule
634+
public TemporaryFolder folder = new TemporaryFolder();
635+
636+
@Test
637+
public void testPath() throws IOException {
638+
Path newFolder = folder.newFolder().toPath();
639+
}
640+
}
641+
""",
642+
"""
643+
import java.io.File;
644+
import java.io.IOException;
645+
import java.nio.file.Path;
646+
import org.junit.Test;
647+
import org.junit.jupiter.api.io.TempDir;
648+
649+
public class TempDirTest
650+
{
651+
@TempDir
652+
public File folder;
653+
654+
@Test
655+
public void testPath() throws IOException {
656+
Path newFolder = newFolder(folder, "junit").toPath();
657+
}
658+
659+
private static File newFolder(File root, String... subDirs) throws IOException {
660+
String subFolder = String.join("/", subDirs);
661+
File result = new File(root, subFolder);
662+
if (!result.mkdirs()) {
663+
throw new IOException("Couldn't create folders " + root);
664+
}
665+
return result;
666+
}
667+
}
668+
"""
669+
)
670+
);
671+
}
616672
}

0 commit comments

Comments
 (0)