TestNG –预期异常测试

在本教程中,我们将向您展示如何使用TestNG的expectedExceptions测试预期的例外在你的代码抛出。

1.运行时异常

本示例说明如何测试运行时异常。 如果方法divisionWithException ()抛出运行时异常– ArithmeticException ,则将传递该异常。

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;
	}

}

以上单元测试将通过。

2.检查异常

复查一个简单的业务对象,保存和更新方法,并在出现错误时引发自定义检查异常。

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");

  }
}

测试预期异常的示例。

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);
  }
	
}

以上单元测试将通过。

下载源代码

下载它– TestNG-Example-Excepted-Exception.zip (11 kb)

参考文献

  1. TestNG ExpectedExceptions JavaDoc

翻译自: https://mkyong.com/unittest/testng-tutorial-2-expected-exception-test/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值