简体   繁体   中英

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;

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". 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM