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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With