dimanche 9 juillet 2017

How can I test methods where I need a file?

I have the class "Password". In this class I have got two public methods, "setPassword" and "getPassword" Here is the code:

public static void setPassword(String password) throws IOException {

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("password", password);

    FileWriter fileWriter = new FileWriter("data/password/" + User.getCurrentUser() + "_password.json");
    fileWriter.write(jsonObject.toJSONString());
    fileWriter.close();
}

public static String getPassword(String user) throws IOException, ParseException {

    File passwordFile = new File("data/password/" + user.toLowerCase() + "_password.json");

    return readPassword(passwordFile);
}

private static String readPassword(File passwordFile) throws IOException, ParseException {

    JSONParser jsonParser = new JSONParser();
    FileReader fileReader = new FileReader(passwordFile);
    Object object = jsonParser.parse(fileReader);

    JSONObject jsonObject = (JSONObject) object;
    fileReader.close();

    return (String) jsonObject.get("password");
}

How can I test this methods with JUnit? Should I use the Mockito-Framework?

Aucun commentaire:

Enregistrer un commentaire