簡體   English   中英

如何使用簡單的junit測試來測試方法(File文件)的參數是否正確,如何測試文件名是否正確?

[英]How to test if the the parameter of the method(File file) is correct using simple junit test, how to test if the file name is correct?

公共 class XML2JSON { 公共 static int PRETTY_PRINT_INDENT_FACTOR = 4;

public DBObject parse(File file) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(file));
    int ptr = 0;
    StringBuilder builder = new StringBuilder();
    while ((ptr = br.read()) != -1) {
        builder.append((char) ptr);
    }
    String xml = builder.toString();

    XmlMapper xmlMapper = new XmlMapper();
    JsonNode node = xmlMapper.readTree(xml.getBytes());
    ObjectMapper jsonMapper = new ObjectMapper();
    String json = jsonMapper.writeValueAsString(node);
    out.println(json);
    return (DBObject) JSON.parse(String.valueOf(json));
}

}

“如何測試文件名是否正確”可以有多種解讀。 如果你想確保給定的文件名是指文件系統中實際存在的文件,只需使用

boolean isCorrect(String filename) {
    return new File(filename).exists();
}

但很可能“文件名是正確的”標准可能會變成“文件必須存在並且是 JSON”。 在那種情況下運行

boolean isCorrect(String filename) {
    try {
        parse(new File(filename))
        return true;
    } catch (Exception e) {
        // either file was not found or could not be parsed
        // find out more via the stack trace
        e.printStackTrace()
        return false;
    }
}

暫無
暫無

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

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