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.
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
- 1Create a solution and library
- 2Create an xUnit test project
- 3Add project references
- 4Write code to test
- 5Write an xUnit test
- 6Run the tests