2017年1月6日 星期五

[.NET Core] Unit Test with xUnit.net

 ASP.NET Core    .NET Core    Unit Test    xUnit.net  


Introduction


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.


Environment


Visual Studio 2015 Update 3  
.Net Core 1.0.0
xunit 2.1.0
dotnet-test-xunit 1.0.0-rc2



Implement


Create a new .NET Core Class Library project





Install packages




Create a simple unit test

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 unit test project, 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 a single one

dotnet test -method Angular2.Mvc.xUnitTest.UnitTestDemo.TestSplitCount



Use [Theory] to test multiple cases(data)


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:






Use [Theory] and [MemberData] to test with expected values

We will refactor the previous unit test and let every test has its own expected value.

First, create a TestCase class with test cases,

Testcase.cs

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;
            }
        }
}


Unit test

[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}");
}


Result








Whaz next?

We will talk about MSTest and decoupling with NSubstitute in the next day-sharing.



Reference




沒有留言:

張貼留言