unit testing for ArgumentNullException by param name
You could explicitly catch the exception in your test and then assert the value of the ParamName
property:
try
{
//test action
}
catch(ArgumentException ex)
{
Assert.AreEqual(expectedParameterName, ex.ParamName);
}
Lee's answer is great, but the test will only fail if an ArgumentException is thrown with the wrong parameter name. If no exception is thrown, the test will pass. To remedy this, I added a bool in my test like this
// Arrange
var expectedParamName = "param";
bool exceptionThrown = false;
// Act
try
{
new Sut(null);
}
// Assert
catch (ArgumentNullException ex)
{
exceptionThrown = true;
Assert.AreEqual(expectedParamName, ex.ParamName);
}
Assert.That(exceptionThrown);