Site icon TestingDocs.com

Testing exceptions in JUnit

Overview

Let’s learn the steps involved in Testing exceptions using JUnit framework. In this post, we will learn how to test methods that throw exceptions in the code. Testing exceptions is common in automation testing, in unit testing or in testing negative test cases. For example, you try to open a non-existent file with the application and check if it throws or handles the exception case. (FileNotFoundException)

We use the clause @Test(expected=<exception class>) to test the method. If the method throws the exception or any subclass of the specified exception class, the method would be marked as pass.

JUnit listing

package com.testingdocs.junit;

/**
* A sample JUnit4 Test demo to test exceptions
*/

/**
* @author testingdocs
*
*/
import static org.junit.Assert.*;
import org.junit.Test;

public class JUnit4ExceptionTest {

@Test(expected=Exception.class)
public void exceptionTest() throws Exception {
//This test will pass as the method code throws
// an exception. This is what expected by the test.
throw new Exception("Sample exception");
}
}

 

 

The test would be marked as pass, even if the test method throws an exception which is a subclass of the specified exception in the @Test expected clause.

 

 

Exception is the super class of FileNotFoundException. Hence, the test is marked as success.

Let’s see another example of unrelated exceptions and the method would be marked as an error by JUnit.

Sample Listing

package com.testingdocs.junit;

/**
 * A sample JUnit4 Test demo to test exceptions
 */

/**
 * @author testingdocs
 *
 */
import static org.junit.Assert.*;
import java.io.IOException;

import org.junit.Test;

public class JUnit4ExceptionTest {

  @Test(expected=IOException.class)
  public void exceptionTest() throws Exception {
    //This test will fail as the method code throws
    // an exception not related to the specified exception
    // in the @Test expected clause.
    throw new ArrayIndexOutOfBoundsException("File Not found exception");
  }
}




 

Exercise:

Run the below code and fill in the blank. You can neglect the package declaration.

Add JUnit4 library to the project.

package com.testingdocs.junit;

/**
 * A sample JUnit4 Test demo to test exceptions
 */

/**
 * @author testingdocs
 *
 */
import static org.junit.Assert.*;
import java.io.IOException;

import org.junit.Test;

public class JUnit4ExceptionTest {

  @Test(expected=IOException.class)
  public void exceptionTest() throws Exception {
    //This test will ____________ (fill in the blank)
    try {
      throw new IOException("File Not found exception");
    }catch(IOException ioe) {

    }
  }
}

 

Now try to run the below code and fill in the blank.

 

JUnit Tutorial on this website can be found at:

https://www.testingdocs.com/junit-tutorial/

More information on JUnit official website:

https://junit.org

 

Exit mobile version