Testing in .NET
Professional .NET development requires comprehensive testing: xUnit for unit tests, Moq for mocking dependencies, integration tests with real databases (TestContainers), and end-to-end API tests with WebApplicationFactory.
45 min•By Priygop Team•Last updated: Feb 2026
Testing Code
Example
// install: dotnet add package xunit; dotnet add package Moq; dotnet add package FluentAssertions
// Service under test
public class OrderService {
private readonly IOrderRepository _repo;
private readonly IEmailService _email;
public OrderService(IOrderRepository repo, IEmailService email) {
_repo = repo; _email = email;
}
public async Task<Order> CreateOrder(CreateOrderDto dto) {
var order = new Order { CustomerId = dto.CustomerId, Total = dto.Total };
await _repo.AddAsync(order);
await _email.SendOrderConfirmation(dto.CustomerId, order.Id);
return order;
}
}
// Unit test with xUnit + Moq
public class OrderServiceTests {
private readonly Mock<IOrderRepository> _repoMock = new();
private readonly Mock<IEmailService> _emailMock = new();
private readonly OrderService _sut;
public OrderServiceTests() =>
_sut = new OrderService(_repoMock.Object, _emailMock.Object);
[Fact]
public async Task CreateOrder_ShouldSaveAndSendEmail() {
// Arrange
var dto = new CreateOrderDto { CustomerId = 1, Total = 99.99m };
_repoMock.Setup(r => r.AddAsync(It.IsAny<Order>())).Returns(Task.CompletedTask);
// Act
var result = await _sut.CreateOrder(dto);
// Assert (FluentAssertions)
result.Should().NotBeNull();
result.Total.Should().Be(99.99m);
_repoMock.Verify(r => r.AddAsync(It.IsAny<Order>()), Times.Once);
_emailMock.Verify(e => e.SendOrderConfirmation(1, It.IsAny<int>()), Times.Once);
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
public async Task CreateOrder_NegativeTotal_ShouldThrow(decimal total) {
var dto = new CreateOrderDto { CustomerId = 1, Total = total };
await _sut.Invoking(s => s.CreateOrder(dto))
.Should().ThrowAsync<ArgumentException>()
.WithMessage("*total*");
}
}
// Integration test with WebApplicationFactory
public class OrdersApiTests : IClassFixture<WebApplicationFactory<Program>> {
private readonly HttpClient _client;
public OrdersApiTests(WebApplicationFactory<Program> factory) =>
_client = factory.WithWebHostBuilder(b =>
b.ConfigureTestServices(s => s.AddSqlite("Data Source=:memory:")))
.CreateClient();
[Fact]
public async Task PostOrder_ReturnsCreated() {
var dto = new { customerId = 1, total = 49.99 };
var response = await _client.PostAsJsonAsync("/api/orders", dto);
response.StatusCode.Should().Be(HttpStatusCode.Created);
}
}