Create a test project, reference the production project, arrange inputs and dependencies, execute one behavior, and assert the observable result. Keep unit tests deterministic and fast; use integration tests when the behavior depends on a real database, filesystem, queue, or HTTP boundary.
```bash
dotnet new xunit -n Shop.UnitTests
dotnet add Shop.UnitTests reference Shop.Application
dotnet test
```
```csharp
public sealed class PriceCalculatorTests
{
[Theory]
[InlineData(100, 0.10, 90)]
[InlineData(50, 0, 50)]
public void ApplyDiscount_ReturnsExpectedTotal(
decimal subtotal, decimal rate, decimal expected)
{
var sut = new PriceCalculator();
decimal actual = sut.ApplyDiscount(subtotal, rate);
Assert.Equal(expected, actual);
}
[Fact]
public void ApplyDiscount_RejectsNegativeSubtotal()
{
var sut = new PriceCalculator();
Assert.Throws<ArgumentOutOfRangeException>(
() => sut.ApplyDiscount(-1, 0.1m));
}
}
```
Name tests around behavior, cover boundaries and failure paths, and avoid asserting private implementation details. CI should run `dotnet test` from a clean checkout.
Krishna Yadav · · 0 likes
Steps to set up and write xUnit tests for a C# project:
1. Create a test project
dotnet new xunit -n Orders.Tests
dotnet add Orders.Tests reference src/Orders/Orders.csproj
dotnet sln add Orders.Tests
The template includes xunit, xunit.runner.visualstudio, Microsoft.NET.Test.Sdk and coverlet.collector. (xUnit v3 is the current major version, with its own templates; the concepts are the same.)
2. Add helper libraries as needed
- Mocking: NSubstitute or Moq.
- Assertions: built-in Assert, or Shouldly (FluentAssertions now requires a commercial licence for business use from v8).
- ASP.NET Core integration tests: Microsoft.AspNetCore.Mvc.Testing.
3. Write tests with [Fact] and [Theory]
public class DiscountServiceTests
{
[Fact]
public void Applies_10_percent_for_gold_customers()
{
// Arrange
var service = new DiscountService();
// Act
var price = service.Apply(1000m, CustomerTier.Gold);
// Assert
Assert.Equal(900m, price);
}
[Theory]
[InlineData(1000, CustomerTier.Silver, 950)]
[InlineData(1000, CustomerTier.Regular, 1000)]
public void Applies_tier_discount(decimal input, CustomerTier tier, decimal expected) =>
Assert.Equal(expected, new DiscountService().Apply(input, tier));
[Fact]
public void Rejects_negative_price() =>
Assert.Throws<ArgumentOutOfRangeException>(() => new DiscountService().Apply(-1, CustomerTier.Gold));
}
4. Mock dependencies
[Fact]
public async Task Sends_email_when_order_is_placed()
{
var email = Substitute.For<IEmailSender>();
var service = new OrderService(email);
await service.PlaceAsync(new Order { Id = 1, CustomerEmail = "a@b.com" });
await email.Received(1).SendAsync("a@b.com", Arg.Any<string>());
}
5. Setup and shared context
- xUnit creates a new instance of the test class per test: use the constructor for setup and IDisposable or IAsyncLifetime for cleanup.
- Share expensive resources with IClassFixture<T> or collection fixtures.
- Use ITestOutputHelper for logging inside tests.
6. Run the tests
dotnet test (add --collect:"XPlat Code Coverage" for coverage), or the Test Explorer in Visual Studio or VS Code.
7. Add to CI
Run dotnet test in the pipeline on every pull request and publish results and coverage.
Good practices: Arrange-Act-Assert, one behaviour per test, descriptive names, deterministic tests (inject time with TimeProvider), no dependence on test order, and integration tests with WebApplicationFactory for API endpoints.