In this tutorial, we will show you how to use the TestNG expectedExceptions to test the expected exception throws in your code.
1. Runtime Exception
This example shows you how to test a runtime exception. If the method divisionWithException () throws a runtime exception – ArithmeticException, it will be passed.
TestRuntime.java
package com.mkyong.testng.examples.exception;
import org.testng.annotations.Test;
public class TestRuntime {
@Test(expectedExceptions = ArithmeticException.class)
public void divisionWithException() {
int i = 1 / 0;
}
}
The above unit test will be passed.
2. Checked Exception
Review a simple business object, save and update method, and throws custom checked exceptions if error.
OrderBo.java
package com.mkyong.testng.project.order;
public class OrderBo {
public void save(Order order) throws OrderSaveException {
if (order == null) {
throw new OrderSaveException("Order is empty!");
}
// persist it
}
public void update(Order order) throws OrderUpdateException, OrderNotFoundException {
if (order == null) {
throw new OrderUpdateException("Order is empty!");
}
// If order is not available in the database
throw new OrderNotFoundException("Order is not exists");
}
}
Example to test the expected exception.
TestCheckedException.java
package com.mkyong.testng.examples.exception;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.mkyong.testng.project.order.Order;
import com.mkyong.testng.project.order.OrderBo;
import com.mkyong.testng.project.order.OrderNotFoundException;
import com.mkyong.testng.project.order.OrderSaveException;
import com.mkyong.testng.project.order.OrderUpdateException;
public class TestCheckedException {
OrderBo orderBo;
Order data;
@BeforeTest
void setup() {
orderBo = new OrderBo();
data = new Order();
data.setId(1);
data.setCreatedBy("mkyong");
}
@Test(expectedExceptions = OrderSaveException.class)
public void throwIfOrderIsNull() throws OrderSaveException {
orderBo.save(null);
}
/*
* Example : Multiple expected exceptions
* Test is success if either of the exception is thrown
*/
@Test(expectedExceptions = { OrderUpdateException.class, OrderNotFoundException.class })
public void throwIfOrderIsNotExists() throws OrderUpdateException, OrderNotFoundException {
orderBo.update(data);
}
}
The above unit test will be passed.
Download Source Code
Download it – TestNG-Example-Excepted-Exception.zip (11 kb)
Pingback: http://www.dotboating.com/user_detail.php?u=companionng9()
Pingback: Manufactured Home Leveling()
Pingback: game addict()
Pingback: larnaca airport taxis()
Pingback: TAS BURBERRY()
Pingback: sexy videos()
Pingback: jokes and riddles for january()
Pingback: fitness()
Pingback: here()
Pingback: Children Education()
Pingback: buy ig followers()
Pingback: https://drive.google.com/file/d/0B_YWbL4BOGpPUVUwdWtld3BTc3c/view?usp=sharing()
Pingback: CHANEL()
Pingback: Tabletki na cellulit()
Pingback: best flight deals()