Skip to content

Commit 822324b

Browse files
committed
fix(java): ensure test code insertion with proper annotation and handling of full code blocks
This commit fixes a bug in the JavaCodeModifier class where test methods without the @test annotation were not being inserted correctly. It also addresses an issue where full code blocks, identified by starting with an import statement and containing a class definition, were not being handled appropriately. The fix includes trimming the code block to remove the surrounding ``` markdown syntax, and then inserting the code as a test method or class, depending on its content and the context of the existing source file.
1 parent 194a837 commit 822324b

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

java/src/main/kotlin/cc/unitmesh/idea/context/JavaCodeModifier.kt

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,21 +28,44 @@ open class JavaCodeModifier : CodeModifier {
2828

2929
fun lookupFile(
3030
project: Project,
31-
sourceFile: VirtualFile
31+
sourceFile: VirtualFile,
3232
) = PsiManager.getInstance(project).findFile(sourceFile) as PsiJavaFile
3333

3434
override fun insertTestCode(sourceFile: VirtualFile, project: Project, code: String): Boolean {
35-
if (!code.contains("@Test")) {
36-
log.warn("methodCode does not contain @Test annotation: $code")
37-
insertMethod(sourceFile, project, code)
35+
// remove surrounding ``` markdown code block
36+
val trimCode = code.trim().removeSurrounding("```").removePrefix("java")
37+
38+
if (!trimCode.contains("@Test")) {
39+
log.warn("methodCode does not contain @Test annotation: $trimCode")
40+
insertMethod(sourceFile, project, trimCode)
3841
return false
3942
}
4043

41-
if (code.startsWith("import") && code.contains("class ")) {
42-
return insertClass(sourceFile, project, code)
44+
val isFullCode = trimCode.startsWith("import") && trimCode.contains("class ")
45+
// check is sourceFile has class
46+
val classes = runReadAction {
47+
val psiJavaFile = lookupFile(project, sourceFile)
48+
psiJavaFile.classes
49+
}
50+
51+
if (classes.isNotEmpty()) {
52+
// replace the last class with the new test class
53+
val lastClass = classes.last()
54+
val classEndOffset = lastClass.textRange.endOffset
55+
56+
WriteCommandAction.runWriteCommandAction(project) {
57+
val document = PsiDocumentManager.getInstance(project).getDocument(lastClass.containingFile)
58+
document?.replaceString(classEndOffset, document.textLength, trimCode)
59+
}
60+
61+
return true
62+
}
63+
64+
if (isFullCode) {
65+
return insertClass(sourceFile, project, trimCode)
4366
}
4467

45-
insertMethod(sourceFile, project, code)
68+
insertMethod(sourceFile, project, trimCode)
4669
return true
4770
}
4871

0 commit comments

Comments
 (0)