通过param名称对ArgumentNullException进行单元测试

Sim*_*mon 6 c# unit-testing mstest dependency-injection

我有一个单元测试,并检查我的控制器构造函数的空异常为几个不同的服务.

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
Run Code Online (Sandbox Code Playgroud)

在我的控制器构造函数中,我有:

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

 if (routeProfileDataService == null)
    throw new ArgumentNullException("routeProfileDataService");
Run Code Online (Sandbox Code Playgroud)

我对每个进行了单元测试,但是如何区分这两者.我可以保持测试,因为任何一个检查都可能抛出null,所以我想通过param名称测试异常.

这可能吗?

Lee*_*Lee 9

您可以在测试中显式捕获异常,然后断言ParamName属性的值:

try
{
    //test action
}
catch(ArgumentException ex)
{
    Assert.AreEqual(expectedParameterName, ex.ParamName);
}
Run Code Online (Sandbox Code Playgroud)