Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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

See this: http://msdn.microsoft.com/en-us/library/ms243315.aspx You can provide the expected message too:

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

Requires two test cases though.

var exception = Assert.Throws<ArgumentNullException>(() => new Sut(...));
Assert.That(exception.ParamName, Is.EqualTo("routeCategoryServices");
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top