TestNG - ожидаемое исключение

TestNG - тест ожидаемого исключения

В этом руководстве мы покажем вам, как использовать TestNGexpectedExceptions для проверки ожидаемых выбросов исключения в вашем коде.

1. Исключение во время выполнения

В этом примере показано, как протестировать исключение времени выполнения. Если методdivisionWithException () вызывает исключение времени выполнения -ArithmeticException, оно будет передано.

TestRuntime.java

package com.example.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.example.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.example.testng.examples.exception;

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.example.testng.project.order.Order;
import com.example.testng.project.order.OrderBo;
import com.example.testng.project.order.OrderNotFoundException;
import com.example.testng.project.order.OrderSaveException;
import com.example.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("example");
  }

  @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 кб)

Рекомендации