Ari*_*ian 0 c# extension-methods unit-testing c#-4.0
我想写一个扩展方法来比较两个对象的一些属性.我写了这段代码:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我想构建项目时,我收到此错误:
'Microsoft.VisualStudio.TestTools.UnitTesting.Assert':静态类型不能用作参数
任何人都可以帮我删除这个错误.谢谢
那么编译器错误消息是相当清楚的:Assert是一个静态类,所以你不能使用它作为扩展方法的参数类型.老实说,目前还不清楚你为什么要这么做.如果你希望能够使用Assert.AreTwoObjectsEqual,你就是不能这样做 - 扩展方法是模仿实例方法,而不是不同类型的静态方法.
我怀疑你应该创建一个自己的静态类,例如MoreAssert,只需将它作为一个普通的静态方法:
public static class MoreAssert
{
public static void AreEqualByProperties(object expected, object actual,
List<string> propertyNames)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
参数名称已更改为符合.NET命名约定.我强烈建议您也使用camelCase名称作为局部变量.我还重新排序了与其他断言一致的参数.
那么你只需要打电话:
MoreAssert.AreEqualByProperties(...);
Run Code Online (Sandbox Code Playgroud)
您也可以考虑使用params string[] propertyNames而不是List<string> propertyNames让它更容易调用.
| 归档时间: |
|
| 查看次数: |
788 次 |
| 最近记录: |