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???)]
Assert. Throws<Exception>(() => SomethingThatThrowsAnException()); If the method SomethingThatThrowsAnException() from the above throws an exception the assertion passes, if it does not throw an exception, the assertion will fail and thereby the test fails. It is as simple as that.
xUnit uses the [Fact] attribute to denote a parameterless unit test, which tests invariants in your code. In contrast, the [Theory] attribute denotes a parameterised test that is true for a subset of data. That data can be supplied in a number of ways, but the most common is with an [InlineData] attribute.
The following xUnit attributes enable writing a suite of similar tests: [Theory] represents a suite of tests that execute the same code but have different input arguments. [InlineData] attribute specifies values for those inputs.
Thereby, the xUnit test eliminates the risk of test method dependencies.
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;
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With