Search code examples
c#unit-testingdependency-injectionmstest

unit testing for ArgumentNullException by param name


I have a unit test and am checking for null exceptions of my controller constructor for a few different services.

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

In my controller constructor I have:

 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 as either of the checks could be throwing null so I want to test the exception by param name.

Is this possible?


Solution

  • 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);
    }