LESSON 2 OF 18

2. First Unit Tests with xUnit and Test Organization

Learn to write your first unit tests with xUnit, use Fact and Theory, apply Arrange-Act-Assert, and organize a maintainable test project.

50 dk 78

Introduction

Creating a test project does not automatically give us a maintainable testing foundation. As a project grows, tests become difficult to read and maintain when their behavior, naming, location, and shared setup are not clear.

In this lesson, we will write our first unit tests with xUnit in the existing .NET solution. We will create a small independent class, apply the Arrange-Act-Assert pattern, compare [Fact] and [Theory], and establish practical naming and folder conventions.

We will not use a real database, HTTP server, or external service in this lesson. The goal is to verify one class quickly and in isolation. Later lessons will build on this foundation with Moq, service tests, and integration tests.

1. The role of a unit test project

A unit test verifies a small unit of application behavior independently from other components whenever possible. A unit test usually focuses on one class or method. Infrastructure dependencies such as databases, file systems, network connections, and external services should not be part of the direct execution path of a focused unit test.

The test project references the production project that it tests. If the solution contains catalog functionality, a structure like this is a useful starting point:

src/  Catalog.Api/  Catalog.Application/  Catalog.Domain/ tests/  Catalog.Application.UnitTests/  Catalog.Api.IntegrationTests/

Keeping tests in a separate project provides several benefits:

  • It keeps unit tests fast and independent from integration tests.
  • It makes the boundaries of the tested application layer visible.
  • It makes it easier to run only fast tests or the complete test suite in CI/CD.

Reference the production project instead of copying its classes into the test project. This ensures that the tests verify the code the application actually uses.

2. Creating the first testable class

As an example, let us create a small class that applies a discount to a product price. It has no database or service dependency, which makes it a good unit-testing target.

namespace Catalog.Application.Pricing; public sealed class PriceCalculator {    public decimal ApplyDiscount(decimal price, decimal discountRate)    {        if (price < 0)            throw new ArgumentOutOfRangeException(nameof(price));        if (discountRate is < 0 or > 1)            throw new ArgumentOutOfRangeException(nameof(discountRate));        return price - (price * discountRate);    } }

This class has three visible behaviors: it calculates a valid price and discount, rejects a negative price, and requires the discount rate to remain between 0 and 1. A useful test set should cover both successful results and error cases.

3. Applying Arrange-Act-Assert

Dividing a test into three sections improves readability:

  1. Arrange: Prepare the objects and inputs required by the test.
  2. Act: Call the method under test, usually once.
  3. Assert: Verify the expected result or behavior.

Let us write the first test:

using Catalog.Application.Pricing; using Xunit; namespace Catalog.Application.UnitTests.Pricing; public sealed class PriceCalculatorTests {    [Fact]    public void ApplyDiscount_WithTwentyPercentDiscount_ReturnsExpectedPrice()    {        // Arrange        var calculator = new PriceCalculator();        const decimal price = 100m;        const decimal discountRate = 0.20m;        // Act        var result = calculator.ApplyDiscount(price, discountRate);        // Assert        Assert.Equal(80m, result);    } }

[Fact] is used for a test that does not require a variable data set and is expected to remain true whenever it runs under the same conditions. The test name should describe observable behavior rather than the internal implementation.

4. Test naming conventions

A test name should explain the behavior even when it appears in a failure list. A common and useful format is:

MethodName_StateUnderTest_ExpectedBehavior

For example:

  • ApplyDiscount_WithTwentyPercentDiscount_ReturnsExpectedPrice
  • ApplyDiscount_WithNegativePrice_ThrowsArgumentOutOfRangeException
  • ApplyDiscount_WithMaximumDiscount_ReturnsZero

Avoid unnecessary implementation details. Describe the business behavior instead of every internal operation. Names such as Test1, ShouldWork, or Method_ReturnsValue make maintenance and failure analysis harder.

5. Testing error cases

When a method throws an exception, verify not only the exception type but also important stable information, such as the rejected parameter. xUnit provides Assert.Throws<T> for this purpose:

[Fact] public void ApplyDiscount_WithNegativePrice_ThrowsArgumentOutOfRangeException() {    // Arrange    var calculator = new PriceCalculator();    // Act and Assert    var exception = Assert.Throws<ArgumentOutOfRangeException>(        () => calculator.ApplyDiscount(-1m, 0.10m));    Assert.Equal("price", exception.ParamName); }

Act and Assert appear together here because the exception is expected while the method is called. The test does not need to verify the complete exception message unless that message is part of a meaningful public contract. Full message assertions are often brittle because wording may change without changing the behavior.

6. Using [Theory] with multiple data sets

Use [Theory] when the same behavior must be verified with several inputs. Every [InlineData] row is executed as a separate test case:

[Theory] [InlineData(100, 0, 100)] [InlineData(100, 0.10, 90)] [InlineData(250, 0.20, 200)] [InlineData(80, 1, 0)] public void ApplyDiscount_WithValidValues_ReturnsExpectedPrice(    decimal price,    decimal discountRate,    decimal expected) {    // Arrange    var calculator = new PriceCalculator();    // Act    var result = calculator.ApplyDiscount(price, discountRate);    // Assert    Assert.Equal(expected, result); }

[Fact] communicates one fixed behavior, while [Theory] communicates that the same behavior holds for different data values. Do not put every scenario into one theory. Keeping related data sets in separate theories can make the test report much easier to understand when a case fails.

7. Organizing test folders and classes

Following the production namespace and folder structure makes tests easier to find. For example:

tests/Catalog.Application.UnitTests/  Pricing/    PriceCalculatorTests.cs  Products/    ProductServiceTests.cs  Common/    TestData.cs

A test class usually takes the name of the class under test and adds the Tests suffix. If one class becomes too large, it can be divided by behavior:

  • PriceCalculatorValidationTests
  • PriceCalculatorDiscountTests
  • PriceCalculatorRoundingTests

Do not split classes prematurely. Start with one focused test class and separate it when it begins to mix responsibilities or becomes difficult to read.

8. Managing shared test setup

If every method in a test class needs the same simple object, create it as a field or in the constructor:

public sealed class PriceCalculatorTests {    private readonly PriceCalculator _calculator = new();    [Fact]    public void ApplyDiscount_WithZeroDiscount_ReturnsOriginalPrice()    {        var result = _calculator.ApplyDiscount(100m, 0m);        Assert.Equal(100m, result);    }    [Fact]    public void ApplyDiscount_WithFullDiscount_ReturnsZero()    {        var result = _calculator.ApplyDiscount(100m, 1m);        Assert.Equal(0m, result);    } }

This is appropriate for simple, immutable, and inexpensive objects. Keep every test independent. If a list, static variable, or shared mutable object is changed by one test and observed by another, the suite becomes dependent on execution order.

For expensive resources such as database connections or test servers, xUnit fixture mechanisms are useful and will be covered later with integration testing. In this lesson, avoiding unnecessary shared state is the safer design.

9. Running tests and interpreting results

Run all tests from the solution root with:

dotnet test

To run one project only:

dotnet test tests/Catalog.Application.UnitTests/Catalog.Application.UnitTests.csproj

When a test fails, first read the expected and actual values. Then inspect the inputs in Arrange, the call in Act, and the expectation in Assert. Do not immediately change the test just to make it green. Decide first whether the behavior contract or the production implementation is incorrect.

Common mistakes

  • Too much behavior in one test: A test should not verify discount calculation, logging, and database updates at the same time.
  • Sharing state between tests: Static collections and shared mutable objects break test isolation.
  • Testing implementation details: Verifying private fields or every internal call can make tests dependent on code structure rather than behavior.
  • Turning everything into a theory: Hiding different behaviors inside data rows can make the test report difficult to understand.
  • Using vague names: If a failed test does not explain what it verifies, rename it.
  • Overbuilding setup: Using real services, files, or databases in a unit test makes it slow and blurs the boundary between unit and integration testing.

Short practice exercise

Add the following tests for PriceCalculator:

  1. Verify that a negative discount rate throws ArgumentOutOfRangeException.
  2. Verify that a discount rate greater than 1 throws the same exception.
  3. Verify that a price of 0 with a discount rate of 0 returns 0.
  4. Use a [Theory] with at least three data rows to test valid prices.
  5. Keep the tests in Pricing/PriceCalculatorTests.cs and make every test name describe the behavior.

Finally, run dotnet test. If you intentionally make one test fail, inspect how the runner identifies the failing data row or expectation.

Conclusion

In this lesson, we wrote our first unit tests with xUnit, distinguished [Fact] from [Theory], and applied Arrange-Act-Assert. We also established behavior-focused test names, a production-aligned folder structure, and careful management of shared setup.

Well-organized tests do more than find bugs: they provide living examples of how the code is expected to behave. In the next lesson, we will address dependencies of the classes under test. This will allow us to verify service behavior in isolation by using controlled test doubles and Moq instead of calling real external services.

Sources