Author : MD TAREQ HASSAN
Understanding Fact and Theory
- Facts are tests which are always true. They test invariant conditions
- Theories are tests which are only true for a particular set of data
We use xUnit Fact when we have some criteria that always must be met, regardless of data. For example, when we test a controller’s action to see if it’s returning the correct view.
xUnit Theory on the other hand depends on set of parameters and its data, our test will pass for some set of data and not the others. We have a theory which postulate that with this set of data, this will happen
Fact Attribute
[Fact]
attribute is used by the xUnit.net test runner to identify a ‘normal’ unit test - a test method that takes no method arguments.
[Fact]
public void ShouldAddDoubleValues()
{
var sut = new Calculator();
double result = sut.AddDoubles(1.1, 2.2);
Assert.Equal(3.3, result, precision: 1);
}
Theory Attribute
[Theory]
attribute expects one or more DataAttribute instances to supply the values for a Parameterized Test’s method arguments
public class ParameterizedTests {
public bool IsOddNumber(int number) {
return number % 2 != 0;
}
[Theory]
[InlineData(5, 1, 3, 9)]
[InlineData(7, 1, 5, 3)]
public void AllNumbers_AreOdd_WithInlineData(int a, int b, int c, int d) {
Assert.True(IsOddNumber(a));
Assert.True(IsOddNumber(b));
Assert.True(IsOddNumber(c));
Assert.True(IsOddNumber(d));
}
}