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?

Viewed 37

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));
}

}

1 Answers

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