测试返回的字符串是否具有java类

我有一个生成java类并写入.java文件的方法。 如何在这个方法上编写unit testing,以确保写入文件的字符串格式是标准的java类格式。

例如:我应检查它是否有包装声明应检查包装是否在课前声明打开和关闭括号等…

这是一个可用于查找Java文件中的编译错误的方法,如果没有生成错误,那么它就是一个完全有效的Java类。

import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class TestMain { public static void main(String[] args) { List sourceList = Arrays.asList(Paths.get("MyJavaClass.java").toFile()); List errorList = new TestMain().compile(sourceList); if(errorList.size() == 0) { System.out.println("No error found, perfectly valid java class"); } else { errorList.forEach(System.out::println); } } public List compile (List javaFileList) { System.out.println("Started compilation"); List errorList = new ArrayList(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector diagnostics = new DiagnosticCollector(); StandardJavaFileManager fileManager = compiler.getStandardFileManager( diagnostics, null, null); Iterable compilationUnits = fileManager .getJavaFileObjectsFromFiles(javaFileList); compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits) .call(); for (Diagnostic diagnostic : diagnostics .getDiagnostics()) { String diagnosticMessage = String.format("Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic.getSource().toUri() + " : \n\t" + diagnostic.getMessage(null)); /*Following gives out of box good message, but I used above to show the custom use of diagnostic * String diagnosticMessage = diagnostic.toString();*/ errorList.add(diagnosticMessage); } try { fileManager.close(); } catch (IOException e) { e.printStackTrace(); } return errorList; } } 

取自最佳处理/处理错误流消息的方法

如果您只想检查它是否是一个有效的Java类(可以编译),您可以尝试。

  try { Class clazz = MyTest.class.getClassLoader().loadClass("TargetClass"); clazz.newInstance(); } catch (Throwable e) { // Not a good idea to catch error, for test purpose only. if(e instanceof Error && e.getMessage().contains("Unresolved compilation problems")){ Assert.fail("Invalid class"); } } 

您可能必须调用“javac”进程(请参阅如何在另一个Java程序中编译和运行java程序? )以确保在运行此测试检查之前TargetClass.class可用。