今天要來談談驗證,還記得之前的PTX範例都只驗證名稱嗎?
1 2 3
| 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驗證參考型別() { Guid ID = Guid.NewGuid(); var expected = new Member { ID = ID, Name = "Name" };
var actual = new Member { ID = ID, Name = "Name" };
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() { Guid ID = Guid.NewGuid(); var expected = new Member { ID = ID, Name = "Name" };
var actual = expected;
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驗證參考型別() { Guid ID = Guid.NewGuid(); var expected = new Member { ID = ID, Name = "Name" };
var actual = new Member { ID = ID, Name = "Name" };
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() {
var actual = new Member { ID = Guid.NewGuid(), Name = "Name" };
actual.Should().NotBeNull(); }
[TestMethod] public void 透過FluentAssertions驗證為Null() {
Member actual = null;
actual.Should().BeNull(); }
|
**
**
驗證數字
1 2 3 4 5 6 7 8 9 10 11 12
| [TestMethod] public void 透過FluentAssertions驗證數字() {
int actual = 123;
actual.Should().Be(123); }
|
驗證趨近於
倍精準相加時會有些微誤差
1 2 3 4 5 6 7 8 9 10 11 12 13
| [TestMethod] public void 透過FluentAssertions驗證趨近於() { var a = 1.3; var b = 0.1; double actual = a + b ;
actual.Should().Be(1.4); }
|
驗證地方可改成
1 2 3 4
|
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驗證升冪排序() { var parameter = new List<int> { 4, 7, 1, 3, 8 }; var actual = parameter.OrderBy(x=>x);
actual.Should().BeInAscendingOrder(); }
[TestMethod] public void 透過FluentAssertions驗證降冪排序() { var parameter = new List<int> { 4, 7, 1, 3, 8 }; var actual = parameter.OrderByDescending(x => x);
actual.Should().BeInDescendingOrder(); }
|
結論
FluentAssertions是個閱讀性高且豐富的驗證套件,以上提供一些我常常使用到的斷言方法,還有很多可以參考官網文件,那今天就先到這了!!