Unit testing for ArgumentNullException by parameter name

I have a unit test and I check for null exceptions of my controller constructor for several different services.

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]

In my controller constructor, I:

 if (routeCategoryServices == null)
    throw new ArgumentNullException("routeCategoryServices");

 if (routeProfileDataService == null)
    throw new ArgumentNullException("routeProfileDataService");

I have a unit test for each, but how can I distinguish between the two. I can leave the test as is, since any of the checks can cause zero, so I want to check the exception by the parameter name.

Is it possible?

+4
source share
3 answers

You can explicitly catch the exception in your test and then confirm the value of the property ParamName:

try
{
    //test action
}
catch(ArgumentException ex)
{
    Assert.AreEqual(expectedParameterName, ex.ParamName);
}
+8
source

: http://msdn.microsoft.com/en-us/library/ms243315.aspx :

[TestMethod]
[ExpectedException(typeof(ArgumentNullException), "routeCategoryServices")]

.

+1

Lee's answer is great, but the test will fail if the ArgumentException is thrown with the wrong parameter name. If an exception is not thrown, the test will pass. To fix this, I added bool to 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);
+1
source

Source: https://habr.com/ru/post/1523883/


All Articles