### [Unit Test] 測試程式中的比對物件

https://dotblogs.com.tw/hatelove/2014/06/06/how-to-assert-two-collection-equal

https://dotblogs.com.tw/hatelove/2016/03/28/compare-object-equality-with-expected-objects

1. FluentAssertions
2. SpecFlow

### 開發環境

• Windows 10 Enterprise x64 CHT
• VS 2015 Update2 Eng
• FluentAssertions 4.9
• SpecFlow 2.1

### FluentAssertions

Nuget 上的 FluentAssertions 提供了相當多的比對方式，其中複雜型別的比對可通過 ShouldBeEquivalentTo | ShouldAllBeEquivalentTo 方法實現

Anonymous Type Compare
Anonymous Collection Type Compare
Anonymous and Name Type Compare

[TestMethod]
public void 具名型別集合和具名型別集合比較()
{
var expected = new List<Product>()
{
new Product { ID=1,Name="pen",Price=2.22m,Remark = "我爸的筆"},
new Product { ID=2,Name="book",Price=4.96m ,Remark = "我爸的書"},
};
var actual = new List<Product>()
{
new Product { ID=1,Name="pen",Price=2.22m,Remark = "我爸的筆"},
new Product { ID=2,Name="book",Price=4.96m ,Remark = "我爸的書"},
};

expected.ShouldBeEquivalentTo(actual);
}

[TestMethod]
public void 匿名型別集合和具名型別集合比較()
{
var expected = new[]
{
new { ID=1,Name="pen",Price=2.22m },
new { ID=2,Name="book",Price=4.96m },
};

var actual = new List<Product>()
{
new Product { ID=1,Name="pen",Price=2.22m,Remark = "我爸的筆"},
new Product { ID=2,Name="book",Price=4.96m ,Remark = "我爸的書"},
};

expected.ShouldBeEquivalentTo(actual);
}

FluentAssertions 只會比 expected 存在的項目，不理會 actual

[TestMethod]
public void 匿名型別和具名型別比較()
{
var expected = new { ID = 1, Name = "pen", Price = 2.22m };
var actual = new Product { ID = 1, Name = "pen", Price = 2.22m, Remark = "我爸的筆" };

expected.ShouldBeEquivalentTo(actual);
}

### SpecFlow

Scenario: SpecFlow比較部分屬性
Given Product資料表應有以下資料
| ID | Name | Price | Remark    |
| 1  | pen  | 2.22  | 我爸的筆   |
| 2  | book | 4.96  | 我爸的書   |
Then 我預期應在Product資料表得到以下資料
| ID | Name | Price |
| 1  | pen  | 2.22  |
| 2  | book | 4.96  |

[Given(@"Product資料表應有以下資料")]
public void GivenProduct資料表應有以下資料(Table table)
{
var products = table.CreateSet<Product>();
}

[Then(@"我預期應在Product資料表得到以下資料")]
public void Then我預期應在Product資料表得到以下資料(Table table)
{
var products = ScenarioContext.Current.Get<IEnumerable<Product>>("products");
table.CompareToSet(products);
}

Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET