Skip to content

Instantly share code, notes, and snippets.

@Codegass
Created August 22, 2023 05:04
Show Gist options
  • Select an option

  • Save Codegass/07cb2e3fa95968ed7f51c0bdd31d26af to your computer and use it in GitHub Desktop.

Select an option

Save Codegass/07cb2e3fa95968ed7f51c0bdd31d26af to your computer and use it in GitHub Desktop.
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.TypeDeclaration;
public class TestCaseExtractor {
public static void extractTestCasesToCSV(String javaFilePath, String csvFilePath) throws Exception {
ASTParser parser = ASTParser.newParser(AST.JLS8); // Use JLS8 for Java 8, adjust if needed
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(readFile(javaFilePath).toCharArray()); // Convert file content to char array
parser.setResolveBindings(true);
parser.setBindingsRecovery(true);
parser.setCompilerOptions(JavaCore.getOptions());
// Parsing the given Java file
org.eclipse.jdt.core.dom.CompilationUnit cu = (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(null);
List<String> testCases = new ArrayList<>();
cu.accept(new ASTVisitor() {
@Override
public boolean visit(MethodDeclaration node) {
if (hasTestAnnotation(node)) {
String testClassName = ((TypeDeclaration) node.getParent()).getName().getIdentifier();
String testCaseName = testClassName + "." + node.getName().getIdentifier();
testCases.add(testCaseName);
}
return true;
}
private boolean hasTestAnnotation(MethodDeclaration method) {
return method.modifiers().stream()
.filter(modifier -> modifier instanceof NormalAnnotation)
.map(annotation -> (NormalAnnotation) annotation)
.anyMatch(annotation -> annotation.getTypeName().getFullyQualifiedName().equals("Test"));
}
});
// Writing to the CSV file
try (FileWriter csvWriter = new FileWriter(csvFilePath)) {
for (String testCase : testCases) {
csvWriter.append(javaFilePath).append(",").append(testCase).append("\n");
}
}
}
private static String readFile(String path) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, Charset.defaultCharset());
}
// ... [Your other methods]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment