XUnit中的理论测试异常

时间:2019-05-08 16:27:47

标签: c# xunit

我使用XUnit进行了以下单元测试:

[Theory]
[InlineData(1, 2, 3)]
[InlineData(-2, 2, 0)]
[InlineData(int.MinValue, -1, int.MaxValue)]
public void CanAddTheory(int value1, int value2, int expected) {
  var calculator = new Calculator();
  var result = calculator.Add(value1, value2);
  Assert.Equal(expected, result);
}

public class Calculator {
  public int Add(int value1, int value2) {

    if (value1 == value2) 
      throw new ArgumentOutOfRangeException();

    return value1 + value2;

  }
}

是否可以使用理论并测试方法是否返回异常?

在此示例中,如果value1 == value2将返回异常:

[InlineData(2, 2, Exception???)]

1 个答案:

答案 0 :(得分:1)

http://dontcodetired.com/blog/post/Testing-for-Thrown-Exceptions-in-xUnitnet

[Theory]
[InlineData(1, 2, 3)]
[InlineData(-2, 2, 0)]
[InlineData(int.MinValue, -1, int.MaxValue)]
public void Calculator_CanAddValidValues(int value1, int value2, int expected) {
  var calculator = new Calculator();
  var result = calculator.Add(value1, value2);
  Assert.Equal(expected, result);
}

[Theory]
[InlineData(1, 1)]
[InlineData(2, 2)]
[InlineData(89, 89)]
public void Calculator_InValidValuesThrowArgumentOutOfRangeException(int value1, int value2) {
  var calculator = new Calculator();
  Assert.Throws<ArgumentOutOfRangeException>(() => calculator.Add(value1, value2);
}

public class Calculator {
  public int Add(int value1, int value2) {

    if (value1 == value2) 
      throw new ArgumentOutOfRangeException();

    return value1 + value2;

  }
}