Loading
 
What's Next: View All Tutorial →

How to test Exception using Junit

A simple @Test method to test exception Class   @Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { new ArrayList<Object>().get(0); } @Test(expected = NullPoint...

Published Date: 20/02/2015  Last Modified Date: 20/02/2015    New Post



A simple @Test method to test exception Class


 
 @Test(expected = IndexOutOfBoundsException.class)
    public void testIndexOutOfBoundsException() {
        new ArrayList<Object>().get(0);
    }

    @Test(expected = NullPointerException.class)
    public void testNullPointerException() {
        String str = null;
        System.out.println(str.toString());
    }

    @Test(expected = IndexOutOfBoundsException.class)
    public void testNullPointerException1() {
        String str = null;
        System.out.println(str.toString());
    }

This does not require any assert statement. This ecpect only the defined expection 

First two test case is passed.


Third Test failed since wrong exception is thrown
Unexpected exception, expected<java.lang.IndexOutOfBoundsException> but was<java.lang.NullPointerException>
java.lang.Exception
Awaiting for Administrator approval





Tags: JUnit

← Back to list


Related Post




×