ชีวิตดีเมื่อใช้ FluentAssertions ช่วยในเขียน test เพื่อเปรียบเทียบ Object ที่ซับซ้อน
สมมติว่าเรามี Data Structure ดังนี้ คำถามคือเราจะ Assert อย่างไร
public class Todo
{
public int ID { get; set; }
public string Title { get; set; }
public bool Completed { get; set; }
}
public class TodoList
{
public IEnumerable<Todo> GetTodoList()
{
return new []
{
new Todo{
ID = 0,
Title = "Shopping",
Completed = false
},
new Todo{
ID = 1,
Title = "Running",
Completed = true
},
new Todo{
ID = 2,
Title = "Reading a book",
Completed = false
}
};
}
}
ถ้าใช้ xUnit อย่างเดียว อาจจะยุ่งยาก ลองใช้ FluentAssertions
Getting Started
-
ติดตั้ง FluentAssertions
dotnet add package FluentAssertions --version 5.10.3
-
เรียก
using FluentAssertions;
แล้วเราสามารถใช้งาน FluentAssertions ได้เลยusing Xunit; using FluentAssertions; public class TodoListTest { [Fact] public void GetTodoListTest() { var todoList = new TodoList(); var expected = new [] { new Todo{ ID = 0, Title = "Shopping", Completed = false }, new Todo{ ID = 1, Title = "Running", Completed = true }, new Todo{ ID = 2, Title = "Reading a book", Completed = false } }; var result = todoList.GetTodoList(); result.Should().BeEquivalentTo(expected); } }
Ref
Cross published at .NET Thailand
Acknowledgement: Thank you .net thailand team to review this article: dotnetthailand.github.io