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.
JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation. Let us see @Test(expected) in action.
When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
The most common cause due to which an IOException is thrown is attempting to access a file that does not exist at the specified location. Common exception classes which are derived from IOException base class are EndOfStreamException, FileNotFoundException, DirectoryNotFoundException etc.
Create Test Runner Class It imports the JUnitCore class and uses the runClasses() method that takes the test class name as its parameter. Compile the Test case and Test Runner classes using javac. Now run the Test Runner, which will run the test case defined in the provided Test Case class. Verify the output.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With