Unit Testing with xUnit and Mocking
Why Test?
Tests are small programs that check your code. They find bugs early, let you change code without fear and document how things should work.
Create a Test Project
bash
dotnet new xunit -n Shop.Tests
cd Shop.Tests
dotnet add reference ../Shop/Shop.csproj
dotnet add package NSubstitute
dotnet test
The Code to Test
csharp
public class PriceCalculator
{
public decimal ApplyDiscount(decimal price, int percent)
{
if (price < 0) throw new ArgumentOutOfRangeException(nameof(price));
if (percent is < 0 or > 100) throw new ArgumentOutOfRangeException(nameof(percent));
return Math.Round(price * (100 - percent) / 100m, 2);
}
}
Arrange - Act - Assert
csharp
using Xunit;
public class PriceCalculatorTests
{
[Fact]
public void ApplyDiscount_TenPercent_ReturnsReducedPrice()
{
// Arrange
var calc = new PriceCalculator();
// Act
var result = calc.ApplyDiscount(200m, 10);
// Assert
Assert.Equal(180m, result);
}
[Theory]
[InlineData(100, 0, 100)]
[InlineData(100, 50, 50)]
[InlineData(100, 100, 0)]
public void ApplyDiscount_ValidInputs_ReturnsExpected(decimal price, int percent, decimal expected)
{
Assert.Equal(expected, new PriceCalculator().ApplyDiscount(price, percent));
}
[Fact]
public void ApplyDiscount_NegativePrice_Throws()
{
var calc = new PriceCalculator();
Assert.Throws<ArgumentOutOfRangeException>(() => calc.ApplyDiscount(-1m, 10));
}
}
| Attribute | Meaning |
|---|---|
[Fact] | One test with no parameters |
[Theory] + [InlineData] | Same test with several data sets |
| Constructor | Runs before every test (xUnit creates a new class instance per test) |
IDisposable.Dispose | Cleanup after every test |
Common Assertions
csharp
Assert.Equal(5, result);
Assert.NotNull(user);
Assert.True(order.IsPaid);
Assert.Contains("error", message);
Assert.Empty(list);
Assert.Equal(3, list.Count);
Assert.InRange(value, 1, 10);
Assert.Equal(1.5, actual, precision: 2);
Mocking Dependencies
A mock is a fake object that replaces a real dependency, such as a database or email sender, so the test stays fast and isolated.
csharp
public interface IEmailSender { Task SendAsync(string to, string subject); }
public interface IOrderRepository { Task<Order?> GetAsync(int id); }
public class OrderService(IOrderRepository repo, IEmailSender email)
{
public async Task<bool> ShipAsync(int orderId)
{
var order = await repo.GetAsync(orderId);
if (order is null) return false;
order.Status = "Shipped";
await email.SendAsync(order.CustomerEmail, "Your order has shipped");
return true;
}
}
csharp
using NSubstitute;
public class OrderServiceTests
{
[Fact]
public async Task Ship_ExistingOrder_SendsEmail()
{
var repo = Substitute.For<IOrderRepository>();
var email = Substitute.For<IEmailSender>();
repo.GetAsync(1).Returns(new Order { Id = 1, CustomerEmail = "ana@example.com" });
var service = new OrderService(repo, email);
var ok = await service.ShipAsync(1);
Assert.True(ok);
await email.Received(1).SendAsync("ana@example.com", Arg.Any<string>());
}
[Fact]
public async Task Ship_MissingOrder_ReturnsFalseAndSendsNothing()
{
var repo = Substitute.For<IOrderRepository>();
var email = Substitute.For<IEmailSender>();
repo.GetAsync(99).Returns((Order?)null);
var ok = await new OrderService(repo, email).ShipAsync(99);
Assert.False(ok);
await email.DidNotReceiveWithAnyArgs().SendAsync(default!, default!);
}
}
Why interfaces? Dependency injection with interfaces is what makes mocking possible. Code that calls
new SmtpClient() inside a method is hard to test.
Good Test Habits
- One behavior per test
- Name:
Method_Scenario_ExpectedResult - Tests must not depend on each other or on order
- No real network, clock or random values: inject them (
TimeProvider) - Test edge cases: null, empty, zero, maximum
Code Coverage
bash
dotnet test --collect:"XPlat Code Coverage"
Coverage is a guide: 100% coverage does not mean no bugs. Focus on important business logic.
Conclusion
Use xUnit for tests, Arrange-Act-Assert for structure, Theory for data-driven cases and NSubstitute to fake dependencies. Interfaces and dependency injection make code testable.
Quick Summary: Fact, Theory, Arrange-Act-Assert, mock external dependencies.

