Testing Exception and Timeout with JUnit

Apart for testing positive scenarios, we would also like to test unexpected scenarios in our applications. There might be scenarios where we expect our application to throw some exception. JUnit supports testing such conditions.

In certain cases we might need our application code to return the response within a particular timespan. In such a situation we can test our application code using timeout testing. We could use JUnit to test such timeout conditions.


Exception Testing

The example below demonstrates exception testing. We create a simple class that divides two numbers. If we try to divide a number by zero the method throws an ArithmeticException.

public class Calculator {
    public int divide(int a, int b){
        if(b==0){
            throw new ArithmeticException();
        }
        return a / b;
    }
}

Next we will write our Test class to test the error scenario.

public class CalculatorTest {
    @Test(expected=ArithmeticException.class)
    public void testInvalidInput(){
Calculator calc = new Calculator(); result = calc.divide(20, 0); } }

We used the 'expected' parameter with the @Test annotation to indicate that the method must throw an Arithmetic Exception.


Timeout Testing

Similar to testing of exception conditions, timeout can also be tested using a parameter in the @Test annotation as shown below:

@Test(timeout=2000)
    public void testFetchResponse(){
        ...
}

The timeout value is expressed in milliseconds. In the above example we have set a timeout of 2000 milliseconds. So, if the execution of the testFetchResponse() method takes more than 2000 milliseconds; the test is marked as failed.

RELATED ARTICLES

Grouping Of Tests using JUnit Categories

JUnit provides the developers with an opportunity to group multiple tests into a single category, thus creating the possibility to include or exclude the category during execution of the test case.

View Article

Unit Testing with JUnit

JUnit is a popular unit testing framework that helps developers to unit test their source code during the development of a java application. This articles demonstrates a basic JUnit Test Case.

View Article

Testing with Multiple Inputs using Parameterized Runner

JUnit Parameterized Test Runners provides the abiltiy to run the same test over and over again using different set of inputs.

View Article

Introducing JUnit Rule

Junit Rules allows developers to add additional functionalities that can applied to all test methods in a test class. It is similar to the concept of custom test runners but with reduced restrictions.

View Article

Understanding JUnit Test Suite

A JUnit Test Suite allows developers to bundle multiple test classes together into a single unit (called as test suite) and run them all together at once.

View Article