2016-04-26 45 views
0

我有一个生成java类并写入.java文件的方法。 如何在这个方法上编写一个单元测试,以确保它写入文件的字符串格式是标准的java类格式。测试返回的字符串是否具有java类

例如:我应该检查它是否有一个包声明 应该检查一下包类声明之前 打开和关闭括号等..

+2

为什么不尝试编译源代码然后对编译的类进行断言? –

回答

0

这里是可以用来查找编译错误的方法一个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<File> sourceList = Arrays.asList(Paths.get("MyJavaClass.java").toFile()); 
     List<String> 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<String> compile (List<File> javaFileList) { 
     System.out.println("Started compilation"); 
     List<String> errorList = new ArrayList<String>(); 
     JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 

     DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); 
     StandardJavaFileManager fileManager = compiler.getStandardFileManager(
       diagnostics, null, null); 

     Iterable<? extends JavaFileObject> compilationUnits = fileManager 
       .getJavaFileObjectsFromFiles(javaFileList); 
     compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits) 
       .call(); 

     for (Diagnostic<? extends JavaFileObject> 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; 
    } 
} 

Best way to process/handle Error stream messages

0

两者如果你只是要检查它是否是一个有效的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的”过程(见how to compile & run java program in another java program?),以确保TargetClass.class是运行此测试检查之前可用。

相关问题