Issue
I am reading a file from its classpath in Java project.
Sample Code:
public static Properties loadPropertyFile(String fileName) {
Properties properties = new Properties();
InputStream inputStream = PropertyReader.class.getClassLoader().getResourceAsStream(fileName);
if (inputStream != null) {
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
} else {
throw new Exception("Property file: [" + fileName + "] not found in the classpath");
}
return properties;
}
It's working fine. I am writing Junit tests for this code. How can I create a scenario for IOException
in properties.load(inputStream)
?
What values should I put in my properties.file to get IOException
?
Solution
Have you considered a mocking framework? Mock the new
operator for Properties to return a mock implementation that throws IOException
when its load
method is called.
mockitio and powermockito will allow you to do this.
Answered By - DaveH
Answer Checked By - Gilberto Lyons (JavaFixing Admin)