簡體   English   中英

測試返回的字符串是否具有java類

[英]Test if the returned string has java class

我有一個生成java類並寫入.java文件的方法。 如何在此方法上編寫單元測試,以確保將其寫入文件的字符串格式為標准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<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;
    }
}

取自處理/處理錯誤流消息的最佳方式

如果只想檢查它是否是有效的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可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM