Domanda

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

È stato utile?

Soluzione

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, e.g. 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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top