Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write junit test cases for IOException

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.

like image 655
user6090970 Avatar asked Apr 05 '16 14:04

user6090970


People also ask

How do you handle IOException in JUnit?

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.

How do you throw an exception in JUnit?

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.

How do I get IOException?

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.

How do I run a JUnit test case?

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.


1 Answers

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.

like image 77
DwB Avatar answered Sep 30 '22 18:09

DwB