简体   繁体   English

使用C#和反射对类进行单元测试属性

[英]Unit testing properties of a class using C# and reflection

I'm facing some difficulties with unit testing in C#. 我在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. 在其他测试方法中,我使用[DataTestMethod][DataRow(stuff)]来提供单个输入并知道导致测试失败的原因。

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? 我想用这种方法检查一致性,是不是错了?

Assert has many interesting properties params! Assert有很多有趣的属性参数!

You can do something like: 你可以这样做:

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

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

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