Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parameter of a class constructor using reflection

I am writing unit tests for a class, and I would like to have individual exception messages when checking each parameter for null.

What I don't know is how to implement GetParameterNameWithReflection method below:

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);
    }
}

As a bonus, comments on the appropriateness of this type of testing are much welcome!

like image 616
heltonbiker Avatar asked Jan 28 '23 01:01

heltonbiker


1 Answers

How about:

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

This asserts that there is exactly one constructor, gets the parameters, asserts there is at least one such and returns the name.

like image 52
Marc Gravell Avatar answered Feb 03 '23 15:02

Marc Gravell