0%

【FluentAssertions】如何驗證巢狀結構中,Double倍精準數

寫單元測試的時候常常會使用FluentAssertions這個套件來做驗證,即便兩個巢狀結構的類別透過這個套件也能輕鬆解決比對問題。

但最近碰到當重狀結構裡面有Double這類的趨近值數值時,驗證會失敗,查了一下後找到解法,所以紀錄一下

原本UnitTest程式長這樣

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
[TestMethod]
public void Test_DoubleAssert()
{
//arrange
var stops = new List<BusStopAPIResult>
{
new BusStopAPIResult
{
StopName = new NameAPIResult
{
Zh_tw = "吊橋頭",
En = "deocioutao"
},
StopUID = "StopUID1",
StopPosition = new BusStopAPIResult.Coordinate
{
PositionLat = 24.853690,
PositionLon = 121.354917
}
},
new BusStopAPIResult
{
StopName = new NameAPIResult
{
Zh_tw = "吊橋頭",
En = "deocioutao"
},
StopUID = "StopUID2",
StopPosition = new BusStopAPIResult.Coordinate
{
PositionLat = 24.853632,
PositionLon = 121.354874
}
}
};

var expected = new List<BusStopClusterDTO>
{
new BusStopClusterDTO
{
Name = "吊橋頭",
SourceID = "StopUID1",
IDs = new List<string> { "StopUID1" , "StopUID2" },
Lat = 24.853661,
Lng = 121.3548955
}
};

//act
var actual = Program.ClusterSourceData(stops);

//assert
actual.ShouldBeEquivalentTo(expected);
}

執行結果如圖

[![](https://2.bp.blogspot.com/-LvpAUuEAqzk/V6P6OrTaInI/AAAAAAAAH3U/37TPKUzXfAI0KKdMpNDAJCpcvBrZXZH2gCLcB/s640/1.png)](https://2.bp.blogspot.com/-LvpAUuEAqzk/V6P6OrTaInI/AAAAAAAAH3U/37TPKUzXfAI0KKdMpNDAJCpcvBrZXZH2gCLcB/s1600/1.png)
[![](https://2.bp.blogspot.com/-xi043e38HW0/V6P6m4ED9_I/AAAAAAAAH3Y/T29FHNHT7h4Y51M1RTmwb1dnZJm-wMLMQCLcB/s320/1.png)](https://2.bp.blogspot.com/-xi043e38HW0/V6P6m4ED9_I/AAAAAAAAH3Y/T29FHNHT7h4Y51M1RTmwb1dnZJm-wMLMQCLcB/s1600/1.png)

因為數值是經緯度,經過計算後不需要驗證精確到小數點這麼多位數,所以可以改用以下方法去驗證

1
2
3
4
5
6
7
actual.ShouldBeEquivalentTo(
expected,
//當欄位型別為Double時,相差到0.000001之內都是OK的
option => option.Using<double>(
ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, 0.000001))
.WhenTypeIs<double>());

這樣驗證就會過關了!!