TestNG


@Test Annotation provides an attribute “expectedExceptions” allowing the user to specify the type of exceptions that are expected to be thrown by a test method during execution.

This is normally used when you are trying to test certain business use cases and validate input data. A simple example is throwing an exception when the division of 2 numbers is not possible because denominator is 0.

expectedExceptions” supports multiple values so you can verify different exceptions.

If the exception thrown by the test method is not part of the user entered list, the test method will be marked as failed.

Here is a quick example

Code

Service Class

package com.skilledmonster.example;

/**
 * Simple calculator service to demonstrate TestNG Framework
 *
 * @author Jagadeesh Motamarri
 * @version 1.0
 */
public interface CalculatorService {

	int sum(int a, int b);

	int multiply(int a, int b);

	int div(int a, int b);

	int sub(int a, int b);

}

Service Implementation Class

package com.skilledmonster.example;

/**
 * Simple calculator service implementation to demonstrate TestNG Framework
 *
 * @author Jagadeesh Motamarri
 * @version 1.0
 */
public class SimpleCalculator implements CalculatorService {

	public int sum(int a, int b) {
		return a + b;
	}

	public int multiply(int a, int b) {
		return a * b;
	}

	public int div(int a, int b) {
		return a / b;
	}

	public int sub(int a, int b) {
		return a - b;
	}

}

Finally, test class using TestNG @Test Annotation’s expectedExceptions attribute

package com.skilledmonster.example;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 * Example to demonstrate use of @Test annotation at method level
 *
 * @author Jagadeesh Motamarri
 * @version 1.0
 */
public class TestNGAnnotationExceptionExample {

	public CalculatorService service;

	@BeforeClass
	public void init() {
		System.out.println("@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.");
		System.out.println("init service");
		service = new SimpleCalculator();
	}

	@Test(expectedExceptions = ArithmeticException.class)
	public void testDiv() {
		System.out.println("@Test : testDiv()");
		int result = service.div(1, 0);
	}

	@Test(expectedExceptions = ArithmeticException.class)
	public void testSum() {
		System.out.println("@Test : testDiv()");
		int result = service.sum(1, 0);
	}

}

Output

 testng_expected_exception_output

As shown in the above console output, testDiv() completed successfully because the method threw an expected exception which is ArithmeticException. On the other hand, testSum() failed because it didn’t throw any exceptions.

Download


Leave a comment