FluentAssertions 的使用

 

做單元測試時,時常需要判斷兩物件裡面的每一個欄位是否一致,
這並不好處理,一做法是實作物件的 Equals 方法來判斷是否一致,範例如下

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
var a = new People() { Id = 1, Name = "Bill", Description = "none" };
var b = new People() { Id = 1, Name = "Bill", Description = "none" };

if (a.Equals(b))
{
Console.WriteLine("ok");
}

public class People : IEquatable<People>
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }

public bool Equals(People other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return this.Id == other.Id && this.Name == other.Name && this.Description == other.Description;
}
}

public interface IEquatable<People>
{
public bool Equals(People other);
};

第二則是利用 FluentAssertions 套件來處理,
如下範例,開一個 xUnit Test Project,
並於 Nuget 安裝好 FluentAssertions 套件,
並填入下面程式碼

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
using FluentAssertions;

namespace TestProject1
{
public class UnitTest1
{
[Fact]
public void Test1()
{
// Arrange
var a = new People() { Id = 1, Name = "Bill", Description = "be modify" };
var b = new People() { Id = 1, Name = "Bill", Description = "none" };

// Act
b = ModifyDescription(b);

// Assert
a.Should().BeEquivalentTo(b, options => options.ExcludingMissingMembers());
}

private People ModifyDescription(People people)
{
people.Description = "be modify";
return people;
}
}
}

public class People
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}

參考資料:
利用FluentAssertions做部分比對或排除特定欄位比對
Test 中驗證 Object 是否相同的方法
Fluent Assertions