Reputation: 39354
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???)]
Upvotes: 8
Views: 6391
Reputation: 2558
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);
}
}
Upvotes: 5
Reputation: 607
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;
}
}
Upvotes: 8