Reputation: 199
I want to check the IOException class in JUNIT testing. Here is my code:
public void loadProperties(String path) throws IOException {
InputStream in = this.getClass().getResourceAsStream(path);
Properties properties = new Properties();
properties.load(in);
this.foo = properties.getProperty("foo");
this.foo1 = properties.getProperty("foo1");
}
when I try to give false properties file path it gives NullPointerException. I want to get IOException and Junit test for it. Thank you very much for your help.
Upvotes: 9
Views: 39454
Reputation: 2288
Check this answer. In short: you can mock the resource that you want to throw an exception and throw the exception by the mock in your tests. Mockito framework might help you with that. The details are under the link I have provided earlier
Upvotes: 0
Reputation: 38328
Try this
public TestSomeClass
{
private SomeClass classToTest; // The type is the type that you are unit testing.
@Rule
public ExpectedException expectedException = ExpectedException.none();
// This sets the rule to expect no exception by default. change it in
// test methods where you expect an exception (see the @Test below).
@Test
public void testxyz()
{
expectedException.expect(IOException.class);
classToTest.loadProperties("blammy");
}
@Before
public void preTestSetup()
{
classToTest = new SomeClass(); // initialize the classToTest
// variable before each test.
}
}
Some reading: jUnit 4 Rule - scroll down to the "ExpectedException Rules" section.
Upvotes: 2
Reputation: 938
Not sure how we simulate the IOException
with the current implementation but if you refactor the code in something like this:
public void loadProperties(String path) throws IOException {
InputStream in = this.getClass().getResourceAsStream(path);
loadProperties(in);
}
public void loadProperties(InputStream in) throws IOException {
Properties properties = new Properties();
properties.load(in);
this.foo = properties.getProperty("foo");
this.foo1 = properties.getProperty("foo1");
}
And create a mocked InputStream, something like this:
package org.uniknow.test;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
public class TestLoadProperties {
@test(expected="IOException.class")
public void testReadProperties() throws IOException {
InputStream in = createMock(InputStream.class);
expect(in.read()).andThrow(IOException.class);
replay(in);
// Instantiate instance in which properties are loaded
x.loadProperties(in);
}
}
WARNING: Created above code on the fly without verifying it by compiling so there might be syntax faults.
Upvotes: -1