使用反射获取类构造函数的参数

hel*_*ker 4 c# reflection unit-testing

我正在为一个类编写单元测试,并且我希望在检查每个参数为null时有单独的异常消息.

我不知道的是如何实现GetParameterNameWithReflection以下方法:

public class struct SUT
{
    public SUT(object a, object b, object c)
    {
        if (a == null)
        {
            throw new ArgumentNullException(nameof(a));
        }

        // etc. for remaining args

        // actual constructor code
    }    
}

[TextFixture]
public class SutTests
{
    [Test]
    public void constructor_shouldCheckForFirstParameterNull()
    {
        var ex = Assert.Throws<ArgumentNullException>(new Sut(null, new object(), new object()));

        string firstParameterName = GetParameterNameWithReflection(typeof(SUT);)

        Assert.AreEqual(firstParameterName, ex.ParamName);
    }
}
Run Code Online (Sandbox Code Playgroud)

作为奖励,非常欢迎对此类测试的适当性的评论!

Mar*_*ell 6

怎么样:

static string GetFirstParameterNameWithReflection(Type type)
{
    return type.GetConstructors().Single().GetParameters().First().Name;
}
Run Code Online (Sandbox Code Playgroud)

这断言只有一个构造函数,获取参数,断言至少有一个这样的并返回名称.