简体   繁体   English

比较两个对象以进行单元测试的扩展方法

[英]Extension method to compare two objects for unit testing

I want to write an extension methods for compare some proprties of two objects. 我想写一个扩展方法来比较两个对象的某些属性。 I wrote this code: 我写了这段代码:

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);
            }
        }
    }

when I want to build the project I get this error: 当我要构建项目时,出现此错误:

'Microsoft.VisualStudio.TestTools.UnitTesting.Assert': static types cannot be used as parameters 'Microsoft.VisualStudio.TestTools.UnitTesting.Assert':静态类型不能用作参数

Can any one help me remove this error.Thanks 谁能帮助我消除此错误。

Well the compiler error message is fairly clear: Assert is a static class, so you can't use that as the parameter type for the extension method. 好吧,编译器错误消息很清楚: Assert是一个静态类,因此您不能将其用作扩展方法的参数类型。 It's not clear why you wanted to in the first place, to be honest. 老实说,目前尚不清楚为什么要这么做。 If you were hoping to be able to use Assert.AreTwoObjectsEqual , you just can't do that - extension methods are meant to mimic instance methods, not static methods in a different type. 如果您希望能够使用Assert.AreTwoObjectsEqual ,那么您就不能这样做-扩展方法旨在模拟实例方法,而不是其他类型的静态方法。

I suspect you should just create a static class of your own, eg MoreAssert , and just make it a normal static method: 我怀疑您应该只创建自己的静态类,例如MoreAssert ,并使其成为普通的静态方法:

public static class MoreAssert
{
    public static void AreEqualByProperties(object expected, object actual,
        List<string> propertyNames)
    {
        ...
    }
}

Parameter names changed to comply with .NET naming conventions. 参数名称已更改为符合.NET命名约定。 I'd strongly encourage you to use camelCase names for local variables, too. 我强烈建议您也将camelCase名称用于局部变量。 I've also reordered the parameters to be consistent with the other assertions. 我还对参数进行了重新排序,使其与其他断言一致。

So then you'd just call: 因此,您只需致电:

MoreAssert.AreEqualByProperties(...);

You might also consider using params string[] propertyNames instead of List<string> propertyNames to make it easier to call. 您也可以考虑使用params string[] propertyNames代替List<string> propertyNames来简化调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM