[英]Extension method to compare two objects for unit testing
我想写一个扩展方法来比较两个对象的某些属性。 我写了这段代码:
public static void AreTwoObjectsEqual(this Assert asr, object Actual, object Expected, List<string> FieldsMustCheck)
{
foreach (string item in FieldsMustCheck)
{
if (Actual.GetType().GetProperty(item) == null || Expected.GetType().GetProperty(item) == null)
{
throw new Exception("Property with name : " + item + " not found in objects ");
}
var ActualPropertyValue = Actual.GetType().GetProperty(item).GetValue(Actual, null);
var ExpectedPropertyValue = Expected.GetType().GetProperty(item).GetValue(Expected, null);
if (ActualPropertyValue != ExpectedPropertyValue)
{
throw new AssertFailedException("Test failed for propery : " + item);
}
}
}
当我要构建项目时,出现此错误:
'Microsoft.VisualStudio.TestTools.UnitTesting.Assert':静态类型不能用作参数
谁能帮助我消除此错误。
好吧,编译器错误消息很清楚: Assert
是一个静态类,因此您不能将其用作扩展方法的参数类型。 老实说,目前尚不清楚为什么要这么做。 如果您希望能够使用Assert.AreTwoObjectsEqual
,那么您就不能这样做-扩展方法旨在模拟实例方法,而不是其他类型的静态方法。
我怀疑您应该只创建自己的静态类,例如MoreAssert
,并使其成为普通的静态方法:
public static class MoreAssert
{
public static void AreEqualByProperties(object expected, object actual,
List<string> propertyNames)
{
...
}
}
参数名称已更改为符合.NET命名约定。 我强烈建议您也将camelCase
名称用于局部变量。 我还对参数进行了重新排序,使其与其他断言一致。
因此,您只需致电:
MoreAssert.AreEqualByProperties(...);
您也可以考虑使用params string[] propertyNames
代替List<string> propertyNames
来简化调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.