magicleon94
magicleon94

Reputation: 5192

Unit testing properties of a class using C# and reflection

I'm facing some difficulties with unit testing in C#.

Let's say I have

class Dummy{
    TypeA Foo {get; set;}
    TypeB Bar {get; set;}
}

and the test method

[TestMethod]
public void TestStuff()
{
    Type type = typeof(Dummy);
    PropertyInfo[] properties = type.GetProperties();

    foreach(PropertyInfo property in properties)
    {
        string result= MyStaticClass.ProcessProperty(property.Name);
        Assert.IsFalse(string.IsNullOrWhiteSpace(result));
    }
}

The test runs fine, but when it fails I have no clue about which property causes the problem.

In other test methods I've used the [DataTestMethod] and [DataRow(stuff)] in order to provide single inputs and know what caused the test to fail.

Is there a way to do something like this using reflection?

Am I thinking of a wrong unit test?

I'd like to use this approach to check consistency, is it wrong at all?

Upvotes: 1

Views: 1973

Answers (1)

Carlos Garcia
Carlos Garcia

Reputation: 2970

Assert has many interesting properties params!

You can do something like:

Assert.IsFalse(string.IsNullOrWhiteSpace(result), $"{property.Name} is null");

Upvotes: 4

Related Questions