There is a java class, it is based on single pattern. how to do unit test for this class? the following is my related code:
public class ConfigFromFile implements ConfigStrategy {
private String endpoint;
private final static String CONFIG_FILE = "/conf/config.properties";
private InputStream getInpustStream(String configFilePath) throws FileNotFoundException{
return new FileInputStream(configFilePath);
}
private void initFromFile(){
Properties prop = new Properties();
InputStream input = null;
try {
input = getInpustStream(CONFIG_FILE);
prop.load(input);
endpoint = prop.getProperty("endpoint");
}catch(Exception e){
e.printStackTrace();
}finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
}
}
}
}
private ConfigFromFile() {
initFromFile();
}
private static class ConfigFromFileHolder {
private static ConfigFromFile instance = new ConfigFromFile();
}
public static ConfigFromFile getInstance() {
return ConfigFromFileHolder.instance;
}
@Override
public String getEndpoint() {
return endpoint;
}
}
I need to write unit test for this class.
- the unit test can't call the external resource, so we need to mock call "/conf/config.properties" file. we can use jmockit.
- this class is based on single pattern. We hope that the interaction between the two cases can not be affected.
The following is my case:
- Case1, it is normal case, the file content is "endpoint=www.baidu.com"
- Case2, it is an abnormal case, we can mock this file does not exist.
how to implement these cases? Thanks!
Aucun commentaire:
Enregistrer un commentaire