xUnit allows our unit test to use parameters, which allows us to test our code for multiple scenarios without needing to write multiple methods with same content.
Let’s look at example from previous lesson
1 2 3 4 5 6 7 8 |
[Fact] public void ShouldReturnSumOfValues() { Program prog = new Program(); int addingResult = prog.Add(3, 9); Xunit.Assert.Equal(12, addingResult); } |
Here we test if 3 + 9 equals 12.
But what if we wanted to test our Add method for multiple scenarios?
We could use InlineData Attribute.
InlineData Attribute allows us to run our test with input parameters, and passes those parameters to test method using params object[] data.
1 2 3 4 5 6 7 8 9 10 11 12 |
[Fact] [InlineData(15,5,10)][InlineData(15,5,10)] [InlineData(55, 4, 51)] [InlineData(99, 33, 66)] public void ShouldReturnSumOfValues(int result, int valueOne, int valueTwo) { Program prog = new Program(); int addingResult = prog.Add(valueOne, valueTwo); Xunit.Assert.Equal(result, addingResult); } |
We are not done yet.
Compiler is not happy and we are getting error : Fact methods cannot have parameters.
Simple solution is to replace Fact Attribute with Theory Attribute
1 2 3 4 5 6 7 8 9 10 11 12 |
[Theory] [InlineData(15,5,10)][InlineData(15,5,10)] [InlineData(55, 4, 51)] [InlineData(99, 33, 66)] public void ShouldReturnSumOfValues(int result, int valueOne, int valueTwo) { Program prog = new Program(); int addingResult = prog.Add(valueOne, valueTwo); Xunit.Assert.Equal(result, addingResult); } |
Now, when we run our unit test we can see that same test method ran 3 times an all test have passed 🙂
Also note that we can also see input parameters!