0%

【Unit Test】Day 7 - Assert

Demo檔案 : Git傳送門

今天要來談談驗證,還記得之前的PTX範例都只驗證名稱嗎?

1
2
3
//assert
Assert.AreEqual(actual.Name, expected);

因為有說如果是參考型別的話,Assert.AreEqual可能會驗證失敗

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[TestMethod]
public void 透過Assert驗證參考型別()
{
//arrange
Guid ID = Guid.NewGuid();
var expected = new Member
{
ID = ID,
Name = "Name"
};

//act
var actual = new Member
{
ID = ID,
Name = "Name"
};

//assert
Assert.AreEqual(expected,actual);
}

結果

試試看改一下寫法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[TestMethod]
public void 透過Assert驗證參考型別2()
{
//arrange
Guid ID = Guid.NewGuid();
var expected = new Member
{
ID = ID,
Name = "Name"
};

//act
var actual = expected;

//assert
Assert.AreEqual(expected, actual);
}

原來Assert.AreEqual當碰到參考型別的時候是驗證記憶體位置,但其實像我是寫商業邏輯的,常常在乎的是透過方法執行完後得到的DTO(Data Transfer Object)是否符合預期,這樣其實Assert對我來說不是那麼方便。

如果我真的只想驗證執行完的DTO內容是否符合預期,該怎麼做呢?來看看FluentAssertions

在單元測試專案用Nuget安裝完成後,來看看範例寫法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[TestMethod]
public void 透過FluentAssertions驗證參考型別()
{
//arrange
Guid ID = Guid.NewGuid();
var expected = new Member
{
ID = ID,
Name = "Name"
};

//act
var actual = new Member
{
ID = ID,
Name = "Name"
};

//assert
actual.ShouldBeEquivalentTo(expected);

}

就這麼簡單,它就會幫你驗證內容的值而不是記憶體位置,而且可讀性也很高,再舉幾個範例

是否為Null

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
[TestMethod]
public void 透過FluentAssertions驗證不為Null()
{
//arrange

//act
var actual = new Member
{
ID = Guid.NewGuid(),
Name = "Name"
};

//assert
actual.Should().NotBeNull();
}

[TestMethod]
public void 透過FluentAssertions驗證為Null()
{
//arrange

//act
Member actual = null;

//assert
actual.Should().BeNull();
}

**


**
驗證數字

1
2
3
4
5
6
7
8
9
10
11
12
[TestMethod]
public void 透過FluentAssertions驗證數字()
{
//arrange

//act
int actual = 123;

//assert
actual.Should().Be(123);
}

驗證趨近於
倍精準相加時會有些微誤差

1
2
3
4
5
6
7
8
9
10
11
12
13
[TestMethod]
public void 透過FluentAssertions驗證趨近於()
{
//arrange
var a = 1.3;
var b = 0.1;
//act
double actual = a + b ;

//assert
actual.Should().Be(1.4);
}

驗證地方可改成

1
2
3
4
//assert
//趨近於1.4 且如果誤差小於0.00001時視為一樣
actual.Should().BeApproximately(1.4,0.00001);

驗證排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[TestMethod]
public void 透過FluentAssertions驗證升冪排序()
{
//arrange
var parameter = new List<int> { 4, 7, 1, 3, 8 };
//act
var actual = parameter.OrderBy(x=>x);

//assert
actual.Should().BeInAscendingOrder();
}

[TestMethod]
public void 透過FluentAssertions驗證降冪排序()
{
//arrange
var parameter = new List<int> { 4, 7, 1, 3, 8 };
//act
var actual = parameter.OrderByDescending(x => x);

//assert
actual.Should().BeInDescendingOrder();
}

結論
FluentAssertions是個閱讀性高且豐富的驗證套件,以上提供一些我常常使用到的斷言方法,還有很多可以參考官網文件,那今天就先到這了!!