Skip to main content

How to set up a .NET project with xUnit tests

Set up a .NET solution with the dotnet CLI: create a class library and an xUnit test project, wire references, write a test, and run it with dotnet test.

Difficulty
Beginner
Duration
35 minutes
Steps
6

What the .NET CLI and xUnit give you

The dotnet command-line interface creates, builds, and tests .NET projects without an IDE. A solution groups related projects, and project references wire them together. xUnit is a widely used .NET testing framework with a clean, attribute-based style. Together they provide a portable, scriptable workflow.

Prerequisites

  • A recent .NET SDK installed
  • A terminal

Steps

1. Create a solution and library

dotnet new sln -n Calc
dotnet new classlib -n Calc.Core
dotnet sln add Calc.Core

2. Create an xUnit test project

dotnet new xunit -n Calc.Tests
dotnet sln add Calc.Tests

3. Add project references

The test project must reference the library it tests.

dotnet add Calc.Tests reference Calc.Core

4. Write code to test

namespace Calc.Core;

public class Calculator
{
    public int Add(int a, int b) => a + b;
}

5. Write an xUnit test

xUnit uses [Fact] for single-case tests and [Theory] for parameterized ones.

using Calc.Core;
using Xunit;

public class CalculatorTests
{
    [Fact]
    public void Add_ReturnsSum()
    {
        Assert.Equal(5, new Calculator().Add(2, 3));
    }
}

6. Run the tests

dotnet test

This builds the solution and runs every test project.

Verification

Run dotnet test and confirm it reports the test as passing. Change the expected value to a wrong number and confirm the run fails with the expected and actual values, then fix it.

Next Steps

Add [Theory] tests with [InlineData], collect coverage with coverlet, organize tests with shared fixtures, and run dotnet test in continuous integration.

Prerequisites

  • .NET SDK installed
  • Basic command line familiarity

Steps

  • 1
    Create a solution and library
  • 2
    Create an xUnit test project
  • 3
    Add project references
  • 4
    Write code to test
  • 5
    Write an xUnit test
  • 6
    Run the tests