有没有一种方法可以编写证明类只有公共成员的单元测试?
我已经对该问题进行了一些研究,并尝试了一些代码,但到目前为止我还没有解决方案。我被困在需要检查是否有私人财产的地步。
//In the unit test
var viewModels = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(a => a.Namespace != null &&
a.Namespace.StartsWith("Test.Solution"))
.Where(t => t.Name.EndsWith("View"))
.ToList();
//ViewModels
public class PersonView {
public string DurationMinutes; // don't take this into consideration
public string Name { get; set; }
public string LastName { get; set; }
private string Number{ get; set; }
// take into consideration only properies with getter and setter
}
答案 0 :(得分:4)
对于类型T
,您可以使用反射来获取非公共属性的数量:
var flags = BindingFlags.NonPublic | BindingFlags.Instance;
var numberOfNonPublicProperties = typeof(T).GetProperties(flags).Length;
答案 1 :(得分:1)
使用Reflection
。基本上,.GetType().GetProperties()
(如果我没记错的话)带有适当的标志。如果您不仅对属性感兴趣,还对字段感兴趣,则还必须包括它们。然后只需检查结果列表是否为空。 LINQ
在这里会很方便。