LoginSignup
3
4

気軽です、.NET 8 + xUnit の標準出力

Posted at

やりたいこと

  • C# の xUnit で実装したユニットテスト内で標準出力を使う

環境

  • Microsoft Visual Studio Community 2022 (64 ビット)
    • Version 17.10.1
  • .NET 8
    • C# 12
  • xunit
    • 2.8.1

手順

1. いつも通りテストクラスを実装

DemoTest.cs
namespace HigeDaruma.DemoXUnit;

public sealed class DemoTest
{
    [Fact]
    public void MathAbs_ReturnsOk_WhenInputValueIsOk()
    {
        // Arrange
        int value = -1;
        int expected = 1;

        // Act
        int result = Math.Abs(value);

        // Assert
        Assert.Equal(expected, result);
    }
}

2. ITestOutputHerlper を使用

ITestOutputHelper を使うことで、テスト エクスプローラーの「テスト詳細の概要」(どっちやねん)に表示することができます。

これをプライマリーコンストラクターで注入し、使用します。

DemoTest.cs
+using Xunit.Abstractions;

namespace HigeDaruma.DemoXUnit;

-public sealed class DemoTest
+public sealed class DemoTest(ITestOutputHelper testOutputHelper)
{
    [Fact]
    public void MathAbs_ReturnsOk_WhenInputValueIsOk()
    {
        // Arrange
        int value = -1;
        int expected = 1;

        // Act
        int result = Math.Abs(value);

        // Assert
        Assert.Equal(expected, result);
+        testOutputHelper.WriteLine($"result: {result}");
    }
}

以前のようにフィールドを用意する必要がなく、一行に満たない変更で標準出力を開始できます。

3. テストを実行してみる

image.png

はい簡単。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4