在 .NET 上使用 xUnit.net 進行單元測試
自從微軟的 .Net Framework 進展到 .Net Core 之後,官方就推薦使用 xUnit 來做單元測試,這裡就進行簡單的介紹。
首先建立一個類別 Student:
public class Student
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;
public Student(string firstName, string lastName)
{
_firstName = firstName;
_lastName = lastName;
}
public string GetFullName()
{
return $"{_firstName} {_lastName}";
}
}
之後新增一個 xUnit 的測試專案,來測試 GetFullName 這個 method。
public class UnitTest1
{
[Fact]
public void Test1()
{
Student student = new Student("Peter", "Liang");
string expectedStr = "Peter Liang";
Assert.NotNull(student);
Assert.Equal(expectedStr, student.GetFullName());
}
[Theory]
[InlineData("Peter", "Chen")]
public void Test2(string firstName, string lastName)
{
Student student = new Student(firstName, lastName);
string expectedStr = $"{firstName} {lastName}";
Assert.Equal(expectedStr, student.GetFullName());
}
}
Test1 很好理解,就是一個很典型的測試案例,測試資料寫在案例裡。不過在 Test2 示範了不同的方式,運用InlineData
這個 attribute 可以同時測試不同組的資料,簡化測試案例裡的程式碼。
參考資料