如何在商業邏輯層進行單元測試

安裝 NSubstitute

安裝 Nuget 的 NSubstitute 套件

1
Install-Package NSubstitute

類別結構

建立模擬物件

建立 Repository 的模擬物件

1
2
3
4
5
6
7
8
Repository mockRepository = Substitute.For<Repository>();

mockRepository
.GetData(Arg.Any<string>())
.Returns(new Table {
Id = 1,
Name = "張三"
});

注入模擬物件

把 Repository 的模擬物件注入 Service

1
Service service = new Service(mockRepository);

使用 Service

1
2
3
Table result = service.RunLogic();

Assert.That(result.Name, Is.EqualTo("張三"));

驗證模擬物件

依傳入參數做回傳

1
2
3
4
5
6
7
8
9
10
11
12
13
mockRepository
.GetData("張三")
.Returns(new Table {
Id = 1,
Name = "張三"
});

mockRepository
.GetData("李四")
.Returns(new Table {
Id = 2,
Name = "李四"
});

模擬呼叫方法多次依序回傳不同內容

1
2
3
4
5
6
7
8
9
10
11
12
13
mockRepository
.GetData(Arg.Any<string>())
.Returns(
new Table
{
Id = 1,
Name = "張三"
},
new Table
{
Id = 2,
Name = "李四"
});

驗證呼叫方法的次數與傳入參數

1
2
3
mockRepository
.Received(1)
.GetData(Arg.Is<string>(x => x == "張三"));

📜 參考資料

  1. NSubstitute文件