[英]Unit testing properties of a class using C# and reflection
我在C#中進行單元測試時遇到了一些困難。
讓我說我有
class Dummy{
TypeA Foo {get; set;}
TypeB Bar {get; set;}
}
和測試方法
[TestMethod]
public void TestStuff()
{
Type type = typeof(Dummy);
PropertyInfo[] properties = type.GetProperties();
foreach(PropertyInfo property in properties)
{
string result= MyStaticClass.ProcessProperty(property.Name);
Assert.IsFalse(string.IsNullOrWhiteSpace(result));
}
}
測試運行正常,但是當它失敗時,我不知道哪個屬性導致問題。
在其他測試方法中,我使用[DataTestMethod]
和[DataRow(stuff)]
來提供單個輸入並知道導致測試失敗的原因。
有沒有辦法用反射做這樣的事情?
我在考慮錯誤的單元測試嗎?
我想用這種方法檢查一致性,是不是錯了?
Assert有很多有趣的屬性參數!
你可以這樣做:
Assert.IsFalse(string.IsNullOrWhiteSpace(result), $"{property.Name} is null");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.