2017 iT 邦幫忙鐵人賽
DAY 24
Modern Web

Learning ASP.NET core + Angular2 系列 第 24

[.NET Core] Unit Test with


One of the MOST IMPORTANT parts on the way to happy coding: Unit Test!
Let us see how to use in .NET Core.


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


Create a new .NET Core Class Library project

Install packages

  1. dotnet-test-xunit
  2. xunit

Create a simple unit test

public class UnitTestDemo
        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

Use [Theory] to test multiple cases(data)

Here is a sample,

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
                List<object[]> tmp = new List<object[]>();
                for (int i = 0; i < Data.Count; i++)
                    tmp.Add(new object[] { i });
                return tmp;
  • UnitTest
[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:

Whaz next?

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


  1. Getting started with (.NET Core / ASP.NET Core)
  2. Stackoverflow : Pass complex parameters to [Theory]

[ASP.NET Core] Configuration
[.NET Core] Unit Test with MSTest
Learning ASP.NET core + Angular2 31