One of the MOST IMPORTANT parts on the way to happy coding: Unit Test!
Let us see how to use xUnit.net in .NET Core.
public class UnitTestDemo
{
[Fact]
public void TestSplitCount()
{
var input = "Luke Skywalker, Leia Skywalker, Anakin Skywalker";
var actual = input.Split(',').Count();
Assert.True(actual.Equals(3), $"Expected:3, Actual:{actual}");
}
}
Build the VStudio solution, and we can see that the unit test is on the Test Explorer
.
Or use the following command to run all tests.
dotnet test
Or run a single one.
dotnet test -method Angular2.Mvc.xUnitTest.UnitTestDemo.TestSplitCount
Here is a sample,
[Theory]
[InlineData("A,B,C")]
[InlineData("AA,BB,CC")]
[InlineData("1,2,3")]
[InlineData("#,^,*")]
public void TestSplitCountComplexInput(string input)
{
var actual = input.Split(',').Count();
Assert.True(actual.Equals(3), $"Expected:3, Actual:{actual}");
}
Test result:
We will refactor the previous unit test and let every test has its own expected value.
First, create a TestCase
class with test cases,
public class TestCase
{
public static readonly List<object[]> Data = new List<object[]>
{
new object[]{"A,B,C",3}, //The last value is the expected value
new object[]{"AA,BB,CC,DD",4},
new object[]{"1,2,3,4,5",5},
new object[]{"(,&,*,#,!,?",6}
};
public static IEnumerable<object[]> TestCaseIndex
{
get
{
List<object[]> tmp = new List<object[]>();
for (int i = 0; i < Data.Count; i++)
tmp.Add(new object[] { i });
return tmp;
}
}
}
[Theory]
[MemberData("TestCaseIndex", MemberType = typeof(TestCase))]
public void TestSplitCountComplexInput(int index)
{
var input = TestCase.Data[index];
var value = (string)input[0];
var expected = (int)input[1];
var actual = value.Split(',').Count();
Assert.True(actual.Equals(expected), $"Expected:{expected}, Actual:{actual}");
}
Test Result:
We will talk about MSTest
and decoupling with NSubstitute
in the next day-sharing.