2

have "Googled the cr*p" out of this one so apologies if the answer is either on here, or fairly simple.

I am writing Unit tests. In this particular one I am instantiating an object using a parameterless constructor. When instantiating using that constructor none of its properties will be set.

I then, as part of the test, want to "loop" through the properties and assert that they are either "null", "0" or "false" (which would be the correct state).

I know it sounds like a dumb thing to do, but if I can do this, then I can write more efficient and readable tests for everything else.

I know I can "loop" through the properties of a "Type", but that's not an instantiated object "of type". It's a "Type" object.

In my head it should be (but obviously isn't) the following:

var target = new MyObject();

foreach(var property in target.GetProperties())
{
    Assert.IsNull(property);
}

Anyone?

LiverpoolsNumber9
  • 2,384
  • 3
  • 22
  • 34
  • possible duplicate of [Programmatic equivalent of default(Type)](http://stackoverflow.com/questions/325426/programmatic-equivalent-of-defaulttype) – nawfal Apr 26 '13 at 04:58

1 Answers1

4

You loop through the properties of the type, and then find the value of each property against an instance of the type:

var target = new MyObject();

foreach(var property in target.GetType().GetProperties())
{
    Type propertyType = property.PropertyType;
    object actual = property.GetValue(target, null);
    object expected = propertyType.IsValueType
        ? Activator.CreateInstance(propertyType)
        : null;
    Assert.AreEqual(expected, actual);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Easy if the class being constructed has a parameterless constructor; otherwise it's a bit harder. Also might be an idea to test against default(T) rather than null to handle value type properties. Not sure off the top of my head how to do this with a System.Type – MattDavey Feb 10 '12 at 11:24
  • So it was completely simple.. thanks Jon. Hopefully might be useful for somebody else coming along in the future. – LiverpoolsNumber9 Feb 10 '12 at 11:26
  • this SO question >http://stackoverflow.com/questions/325426/c-sharp-programmatic-equivalent-of-defaulttype< has a bit more info for handling value type properties. – MattDavey Feb 10 '12 at 11:28
  • @MattDavey: Have added expectations for value types (missed that before). I'm assuming that as the class under test is the one we're constructing an instance of, it doesn't matter whether or not there's a parameterless constructor. – Jon Skeet Feb 10 '12 at 11:36
  • Jon / Matt, I've done a similar thing myself - understood that "Assert.IsNull(property)" wouldn't cover everything anyway - was just using it as a quick way to show the example. Thanks again for your help. – LiverpoolsNumber9 Feb 10 '12 at 11:44