heltonbiker
heltonbiker

Reputation: 27575

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!

Upvotes: 4

Views: 2324

Answers (2)

Slappywag
Slappywag

Reputation: 1223

This method will return the first parameter name of the first constructor. You could expand on this for dealing with multiple constructors and different parameters. It uses the ParameterInfo class.

    public string GetFirstParameterNameWithReflection(Type t)
    {
        return t.GetConstructors()[0].GetParameters()[0].Name;
    }

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062820

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.

Upvotes: 6

Related Questions