I have below code which reads CSV file and puts the values into HashMap on application startup. I am new to Junit, please suggest how to test below class.
@Component
public class Cache implements InitializingBean {
private static Map<String, String> map = new HashMap<>();
@Override
public void afterPropertiesSet() throws Exception {
try {
BufferedReader reader = new BufferedReader(new FileReader("file.csv"));
String details = null;
while ((details = reader.readLine()) != null) {
String[] values = details.split(",", 2);
String firstString = values[0];
String secondString = values[1];
map.put(firstString, secondString);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You don't have to test
BufferedReaderand you can't useMockitohere because you manually instantiate objects in code. Just split up your code: move out reading logic into new method (readCsvFile()for example) and write tests for it.Then you can write a test for the Cache bean so that it isn't empty after startup