[英]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?
public class XML2JSON { public static int PRETTY_PRINT_INDENT_FACTOR = 4;公共 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));
}
} }
"How to test if the filename is correct" can be interpreted in multiple ways. “如何测试文件名是否正确”可以有多种解读。 If you want to ensure the given filename refers to an actually existing file in the filesystem, simply use如果你想确保给定的文件名是指文件系统中实际存在的文件,只需使用
boolean isCorrect(String filename) {
return new File(filename).exists();
}
But very likely the "filename is correct" criteria may become a "file has to exist and be JSON".但很可能“文件名是正确的”标准可能会变成“文件必须存在并且是 JSON”。 In that case run在那种情况下运行
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.