Unit Testing in .NET: xUnit, Moq, and Testing Best Practices

A practical walkthrough of testing in .NET with xUnit v3 and Moq — project setup, Fact vs. Theory, Arrange-Act-Assert, mocking dependencies, and the habits that separate a test suite people trust from one they route around.

Ask around at any mid-level or senior .NET interview and testing comes up early not “do you know what a unit test is,” but “walk me through how you’d test this.” It’s one of the most reliable signals of production experience a hiring manager has, and it’s also one of the easiest things to demonstrate publicly. This is a practical walkthrough of testing in .NET with xUnit and Moq, plus the habits that separate a test suite people actually trust from one they route around.

Contents

Setting Up a Test Project

xUnit is the most widely used testing framework in the .NET ecosystem, and version 3, current as of .NET 10, compiles test projects to standalone executables rather than libraries, which means faster, simpler execution with no cross-process boundaries.

The xunit3 template isn’t built into the SDK, so install it once per machine before using it for the first time:

dotnet new install xunit.v3.templates

Then create the project:

dotnet new xunit3 -n MyApp.Tests
cd MyApp.Tests
dotnet add reference ../MyApp/MyApp.csproj
dotnet add package Moq

Run the suite with:

dotnet test

If your project targets .NET 10, you can opt into the newer Microsoft.Testing.Platform runner (instead of the older VSTest pipeline) by adding this to global.json:

{
  "test": {
    "runner": "Microsoft.Testing.Platform"
  }
}

MTP mode gives you a genuinely standalone test executable with faster startup and a simpler command-line surface, worth adopting on any new project. On .NET 10, the xunit3 template generates or updates this global.json for you automatically, so you often won’t need to write it by hand.

Fact vs. Theory

xUnit has two core test attributes. [Fact] marks a test that always runs the same way:

[Fact]
public void Add_ReturnsSum_OfTwoPositiveNumbers()
{
    var result = Calculator.Add(2, 3);
    Assert.Equal(5, result);
}

[Theory] marks a test that runs multiple times with different inputs, supplied via [InlineData] or a member:

[Theory]
[InlineData(2, 3, 5)]
[InlineData(-1, 1, 0)]
[InlineData(0, 0, 0)]
public void Add_ReturnsExpectedSum(int a, int b, int expected)
{
    var result = Calculator.Add(a, b);
    Assert.Equal(expected, result);
}

Reach for Theory any time you find yourself copy-pasting the same test body with different numbers, it’s the same test, run several ways, and it reads as one.

Anatomy of a Good Test: Arrange, Act, Assert

Every well-structured unit test follows the same three-part shape, and it holds up whether the test is trivial or, like the one below, involves mocking a dependency with Moq.

aaa-anatomy

Arrange sets up everything the test needs – objects, mock behavior, initial state.

Act calls the single thing actually under test, ideally one line.

Assert checks the outcome, and with Moq, can also verify that a collaborator was called the way you expected.

Mocking with Moq

Moq lets you create a fake implementation of an interface and control exactly how it behaves, without writing a hand-rolled stub class. The core API is small:

var pricingService = new Mock<IPricingService>();

// Configure a return value
pricingService.Setup(p => p.GetDiscount(It.IsAny<Customer>())).Returns(0.1m);

// Or throw
pricingService.Setup(p => p.GetDiscount(null)).Throws<ArgumentNullException>();

// Pass the fake object anywhere IPricingService is expected
var cart = new ShoppingCart(pricingService.Object);

// Later, verify it was actually called
pricingService.Verify(p => p.GetDiscount(customer), Times.Once);

It.IsAny<T>() matches any argument of that type when you don’t care about the exact value; use a specific value or a predicate (It.Is<T>(x => ...)) when you do. Verify is what turns Moq from “a way to fake dependencies” into “a way to test that your code called the right things” useful for testing side effects like logging, sending an email, or writing to a repository, where the return value alone doesn’t tell the whole story.

Testing Best Practices

Code that compiles and a test suite that passes aren’t the same thing as a test suite that’s actually useful. These are the habits worth building early.

best-practices

A couple of these deserve a bit more explanation.

Mock boundaries, not everything means: mock the database, the HTTP client, the system clock – things that are slow, non-deterministic, or external. Don’t mock every internal class just because you can; a test suite where everything is mocked stops testing real behavior and starts testing whether your mocks agree with each other.

Treat test code like production code cuts both ways, it deserves the same code review attention, but it also deserves the same willingness to delete something that’s no longer pulling its weight. A flaky or redundant test that people learn to ignore is actively worse than having no test at all.

Wrapping Up

None of this requires exotic tooling, dotnet new xunit3, a Moq package reference, and the AAA pattern cover the vast majority of unit testing you’ll do in a typical .NET codebase. What actually separates strong test suites from weak ones isn’t the framework, it’s discipline: fast, independent, clearly named tests that fail for exactly one reason. That discipline is also precisely what shows up in a code review or a take-home interview project and quietly signals “this person has shipped production code before.”

Frequently Asked Questions

What’s the difference between xUnit v2 and v3?

The headline change is that v3 test projects compile to standalone executables instead of libraries, which removes the cross-process overhead of older test runners and enables native support for Microsoft.Testing.Platform on .NET 10.

Do I need to install anything before running dotnet new xunit3?

Yes. The xunit3 template comes from the xunit.v3.templates NuGet package, not the .NET SDK itself. Run dotnet new install xunit.v3.templates once per machine before the template is available.

When should I use Theory instead of Fact?

When you find yourself writing nearly identical [Fact] tests that only differ in their input values. A single [Theory] with multiple [InlineData] entries replaces them with one test definition run several times.

Should I mock every dependency in a unit test?

No. Mock things that are slow, non-deterministic, or external — a database, an HTTP client, the system clock. Mocking every internal class as well turns the test into a check that your mocks agree with each other rather than a check of real behavior.

What does Moq’s Verify actually check?

It confirms a specific method was called on a mock, optionally with specific arguments and a specific number of times (Times.Once, Times.Never, and so on). It’s how you test side effects — like a call to a logger or a repository — where there’s no return value to assert on directly.

Sources