通过参数名称对ArgumentNullException进行单元测试 [英] unit testing for ArgumentNullException by param name

查看:243
本文介绍了通过参数名称对ArgumentNullException进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单元测试,正在检查我的控制器构造函数对一些不同服务的空异常。

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

我每个人都有单元测试,但是如何区分两者。我可以按原样保留测试,因为任何一项检查都可能抛出null,因此我想按参数名称测试异常。

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.

这可能吗?

推荐答案

您可以明确捕获异常在测试中,然后声明 ParamName 属性的值:

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

这篇关于通过参数名称对ArgumentNullException进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆