[C#] Introduction to xUnit.net and Writing Basic Unit Tests

目次

Overview

This implementation introduces “xUnit.net,” a widely used testing framework in .NET development, and demonstrates the minimal test code required to verify method behavior. It covers the steps to build an automated testing environment compatible with Visual Studio and CI/CD pipelines, along with basic assertion techniques.

Specifications (Input/Output)

  • Input: Target methods (logic) and expected results.
  • Output: Test status (Pass/Fail).
  • Required Packages:
    • Microsoft.NET.Test.Sdk
    • xunit
    • xunit.runner.visualstudio
    • coverlet.collector

Basic Usage

First, run the following commands in your test project directory to install the necessary libraries:

dotnet add package Microsoft.NET.Test.Sdk
dotnet add package xunit
dotnet add package xunit.runner.visualstudio
dotnet add package coverlet.collector

Next, create a test class and write your verification logic:

[Fact]
public void Sum_ReturnCorrectValue()
{
    // Verify that 3 + 5 equals 8
    Assert.Equal(8, Sum(3, 5));
}

Full Code Example

The following example uses a standard namespace and class structure. It demonstrates the Arrange-Act-Assert (AAA) pattern.

using Xunit;

namespace TechBlog.Tests
{
    public class CalculationTests
    {
        /// <summary>
        /// By attaching the [Fact] attribute, this method is recognized and executed by the test runner.
        /// </summary>
        [Fact]
        public void Sum_TwoNumbers_ReturnsCorrectTotal()
        {
            // Arrange
            int value1 = 10;
            int value2 = 20;
            int expected = 30;

            // Act
            // Call the method under test
            int actual = Sum(value1, value2);

            // Assert
            // Verify if the expected value matches the actual value
            Assert.Equal(expected, actual);
        }

        // Target logic
        // Typically, this would reference a class in another project.
        // It is placed here for simplicity.
        private int Sum(int a, int b)
        {
            return a + b;
        }
    }
}

Customization Points

  • Test Method Naming: Using the format MethodName_Condition_ExpectedResult (e.g., Sum_NegativeNumbers_ReturnsZero) makes it easier to understand the test intent from the test list.
  • Data-Driven Testing: By using [Theory] and [InlineData] instead of [Fact], you can test multiple input patterns at once.
  • Async Method Testing: Changing the return type to async Task (e.g., public async Task TestName()) allows for testing asynchronous operations involving await.

Important Notes

  • Access Modifiers: xUnit test classes and methods must be public. The test runner cannot detect internal or private members.
  • Assertion Argument Order: In Assert.Equal, it is conventional to pass the “Expected” value as the first argument and the “Actual” value as the second. If reversed, the logic remains correct, but failure messages (e.g., “Expected: X, Actual: Y”) will be misleading.
  • Package Updates: If xunit.runner.visualstudio is outdated, tests may not appear in the Visual Studio Test Explorer. Always ensure you are using a recent version.

Advanced Usage

Verifying Multiple Input Patterns Simultaneously

The following example uses [Theory] to define multiple cases, including boundary and negative values, within a single method.

[Theory]
[InlineData(1, 2, 3)]
[InlineData(100, 200, 300)]
[InlineData(-5, 5, 0)]
public void Sum_MultipleInputs_ReturnsCorrectTotal(int a, int b, int expected)
{
    var result = Sum(a, b);
    Assert.Equal(expected, result);
}

Summary

Setting up xUnit.net is completed simply by adding NuGet packages. Test code is written inside methods marked with the [Fact] attribute, and comparisons with expected values are performed using the Assert class. It is best to start with simple logic verification and gradually increase test coverage using features like parameterized tests (Theory).

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次