Test Exception with Theory in XUnit
Asked Answered
N

2

8

I have the following Unit test using 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;

  }
}

Is there to use a Theory and also test if a method returns an exception?

In this example an exception would be returned if value1 == value2:

[InlineData(2, 2, Exception???)]
Neldanelia answered 8/5, 2019 at 16:27 Comment(5)
I'd suggest a different test to check for the exception anyway, you're testing a different thing.Kitten
Are you trying to add this exception test to the existing theory? You could always add a separate [Fact] or a [Theory] with different parameters and use Assert.Throws() as the test.Alon
I can see it making sense if you wanted to test multiple inputs that all result in the same exception. But there wouldn't be any point in mixing the two.Dissipated
I will create a different test for the exception. Thank you for the input.Neldanelia
No, because Inline attribute accepts only constant values as a parameters. Exception is not.Straitlaced
R
8

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;

  }
}
Raker answered 16/9, 2019 at 14:50 Comment(0)
T
5

I got it working like this..

[Theory]
[InlineData("", typeof(ArgumentException),"invalid name")]
[InlineData(null, typeof(ArgumentNullException), "name cannot be null")]
public void some_test(string name, Type exceptionType, string message){
  
  var project = new Project();
  
  try {
   project.updateName(name);
  } 
  catch (Exception e){
      Assert.True(e.GetType() == exceptionType);
      Assert.Equal(e.Message,message);
  }

}
Tatia answered 3/3, 2022 at 18:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.