Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท .NET, Tools and Concepts

Testing in .NET

Reference for testing in .NET: test frameworks, the dotnet test command, Arrange-Act-Assert, fakes, theories, and a runnable mini test runner.

A unit test is a small program that calls your code with known input and checks the result. .NET has three mainstream test frameworks: xUnit, NUnit and MSTest. All three discover methods marked with an attribute, run them, and report which ones failed. The dotnet test command builds the test project and runs everything it finds.

The frameworks ship as NuGet packages, so you cannot run them in this site's editors. This page shows their real syntax in read-only blocks and then builds a tiny test runner you can run here, so you can see what the frameworks do for you.

C#
public class PriceTests
{
    [Fact]
    public void Discount_reduces_price()
    {
        Assert.Equal(90m, Pricing.Discount(100m, 10));
    }
}

Try it

The runner below finds methods marked with a custom [Check] attribute using reflection, runs each one and counts failures. This is the core loop every framework implements, plus a lot of polish (parallelism, reporting, filters).

C# A mini test runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Real tests should not depend on slow or external things. Pass dependencies in through an interface and give the test a hand-written fake (see Mocking and fakes).

C# Arrange, Act, Assert with a fake

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

The same test in the three frameworks (read-only; these packages are not available here):

C#
// xUnit: a new class instance per test; constructor = setup, IDisposable = teardown
public class CalcTests
{
    [Fact]
    public void Adds() => Assert.Equal(5, Calc.Add(2, 3));

    [Theory]
    [InlineData(1, 1, 2)]
    [InlineData(-1, 1, 0)]
    public void AddsMany(int a, int b, int expected) => Assert.Equal(expected, Calc.Add(a, b));
}

// NUnit
[TestFixture]
public class CalcTests
{
    [SetUp] public void Setup() { }
    [Test] public void Adds() => Assert.That(Calc.Add(2, 3), Is.EqualTo(5));
    [TestCase(1, 1, 2)] public void AddsMany(int a, int b, int e) => Assert.That(Calc.Add(a, b), Is.EqualTo(e));
}

// MSTest
[TestClass]
public class CalcTests
{
    [TestMethod] public void Adds() => Assert.AreEqual(5, Calc.Add(2, 3));
    [DataTestMethod, DataRow(1, 1, 2)] public void AddsMany(int a, int b, int e) => Assert.AreEqual(e, Calc.Add(a, b));
}

Typical commands:

TEXT
dotnet new xunit -o MyApp.Tests
dotnet add MyApp.Tests reference MyApp
dotnet test
dotnet test --filter "FullyQualifiedName~CalcTests"
Concept xUnit NUnit MSTest
Single test [Fact] [Test] [TestMethod]
Data-driven test [Theory] + [InlineData] [TestCase] [DataRow]
Setup per test constructor [SetUp] [TestInitialize]
Teardown per test IDisposable.Dispose [TearDown] [TestCleanup]
Expect an exception Assert.Throws<T> Assert.Throws<T> Assert.ThrowsExactly<T>

Usage notes

  • Arrange, Act, Assert. Set up the objects, perform one action, then check the outcome. One reason to fail per test makes failures easy to read.
  • Name tests after behavior, such as Discount_reduces_price, not Test1. The name is the first thing you see in a failure report.
  • Fresh state per test. xUnit creates a new class instance for every test method, so instance fields never leak between tests. Tests that share static state become order-dependent and flaky.
  • Floating point: compare double with a tolerance (Assert.Equal(0.3, a + b, precision: 5) in xUnit); exact equality fails on rounding. Prefer decimal for money.
  • Async tests return Task and use await. An async void test method may pass before its work finishes, which is a classic mistake.
  • Test doubles: a fake is a working simplified implementation, a stub returns canned answers, a mock also verifies calls. Mocking libraries (Moq, NSubstitute) are NuGet packages; hand-written fakes need nothing extra.
  • Integration tests start a real slice of the app. For ASP.NET Core, WebApplicationFactory<Program> runs the pipeline in memory (Integration testing).
  • Coverage is a hint, not a goal. 100% line coverage does not mean the assertions are meaningful.
  • Which framework? xUnit is the most common for new open-source code, NUnit and MSTest are equally capable; pick what your team knows. Newer projects can also use the lighter Microsoft.Testing.Platform runner instead of the older VSTest one.