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

标签 c# unit-testing reflection

我正在为一个类编写单元测试,我希望在检查每个参数是否为 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);
    }
}

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

最佳答案

怎么样:

static string GetFirstParameterNameWithReflection(Type type)
{
    return type.GetConstructors().Single().GetParameters().First().Name;
}

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

关于c# - 使用反射获取类构造函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53668814/

相关文章:

c# - 方法来回 'rock'一个值

c# - FlowLayoutPanel 中奇怪的空格

c# - 异步按钮事件有时不起作用

java - 使用 PowerMockito 模拟内部类中的 final方法

java - 获取类中特定对象的注释

c# - EventTriggerBehavior Taped 未触发

c - 在单元测试过程代码时删除依赖项

ruby-on-rails - Rspec:无论测试如何,堆栈级别都太深

java - 如何从java反射中的方法获取 "genericInfo"

c# - 调用类型的空默认构造函数