简体   繁体   中英

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

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. 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.

I suspect you should just create a static class of your own, eg MoreAssert , and just make it a normal static method:

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

Parameter names changed to comply with .NET naming conventions. I'd strongly encourage you to use camelCase names for local variables, too. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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