1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

xUnit.netで単体テストを行う

Posted at

xUnit.netを使って単体テストを行えるようにする。

最終形は以下になる。

C:\src
└─example
    ├─Example
    │  ├─Example.csproj
    │  └─Program.cs
    └─ExampleTests
        ├─ExampleTests.csproj
        └─ProgramTest.cs

開発対象のプロジェクトを作成する

開発対象のプロジェクトを作成する。

cd C:\src
mkdir example
cd example

mkdir Example
cd Example
dotnet new console

開発対象のコードを書く。

Example\Program.cs
namespace Example;

public class Program
{
    public static int Sum(int a, int b)
    {
        return a + b;
    }

    public static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

xUnit.net v3 をインストールする

インストールしていない場合はインストールする。

dotnet new install xunit.v3.templates

単体テストのプロジェクトを作成する

cd ..
mkdir ExampleTests
cd ExampleTests
dotnet new xunit3

単体テストのプロジェクトファイルのターゲットフレームワークを本体のプロジェクトのものと合わせる。

ExampleTests\ExampleTests.csproj
<Project Sdk="Microsoft.NET.Sdk">
    <!-- 略 -->
    <TargetFramework>net9.0</TargetFramework>
    <!-- 略 -->
</Project>

ソリューションファイルとプロジェクトファイルについて設定する。

cd ..

rem ソリューションファイルに単体テストのプロジェクトを追加する
dotnet sln add ExampleTests

rem 単体テストのプロジェクトに本体のプロジェクトの参照を追加する
dotnet add ExampleTests\ExampleTests.csproj reference Example\Example.csproj

単体テストのコードを書く。

ExampleTests\ProgramTest.cs
using Example;

namespace ExampleTests;

public class ProgramTest
{
    [Fact]
    public void Test1()
    {
        Assert.Equal(2, Program.Sum(1, 1));
    }
}

単体テストを実行する

dotnet test

VSCode で開発している場合は左のフラスコのアイコンからテストを実行することができる。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?