vendredi 7 décembre 2018

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

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





Aucun commentaire:

Enregistrer un commentaire