找回密码
 FreeOZ用户注册
查看: 1326|回复: 1
打印 上一主题 下一主题

[学习深造] C# unit test async method throw ArgumentNullException

[复制链接]
跳转到指定楼层
1#
发表于 4-12-2013 19:01:21 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?FreeOZ用户注册

x
大家好,

我有一个method需要unit testing

using Microsoft.VisualStudio.TestTools.UnitTesting;
        public async Task Test(string sql)
        {
            if (string.IsNullOrWhiteSpace(sql))
            {
                throw new ArgumentNullException("sql");
            }

                ......

        }

我现在可以用下面的代码来测试,没问题
        [TestMethod]
        public void ParameterEmpty_ExpectedException()
        {
                ......
            try
            {
                xxx.Test(string.Empty).Wait();
            }
            catch (AggregateException ae)
            {
                Assert.AreEqual(1, ae.InnerExceptions.Count);
                Assert.IsTrue(ae.InnerExceptions[0] is ArgumentNullException);
            }
        }

但我想如下面一样仅在头上加,问题是AggregateException太广了,我想指定InnerExceptions是ArgumentNullException,该如何写啊?
        [TestMethod]
        [ExpectedException(typeof(AggregateException))]
        public void ParameterEmpty_ExpectedException()
谢谢
回复  

使用道具 举报

2#
 楼主| 发表于 5-12-2013 05:45:37 | 只看该作者
本帖最后由 DDD888 于 5-12-2013 06:04 编辑

Here is my solution.

Add a class

namespace UnitTestBase
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    public delegate Task ActionAsync();

    public static class MyAssert
    {
        public static async Task ThrowsAggregateInnerException(ActionAsync action)
        {
            try
            {
                await action.Invoke();
            }
            catch (AggregateException aggregateException)
            {
                throw aggregateException.InnerExceptions.Single();
            }

            Assert.Fail("An aggregateException was expected, but not thrown");
        }
    }
}

Here is the test code.
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public async Task ParameterEmpty_ExpectedException()
{
                ......
            await MyAssert.ThrowsAggregateInnerException(async () => await xxx.Test(string.Empty));
}
        
回复  

使用道具 举报

您需要登录后才可以回帖 登录 | FreeOZ用户注册

本版积分规则

小黑屋|手机版|Archiver|FreeOZ论坛

GMT+11, 8-11-2026 18:27 , Processed in 0.010917 second(s), 17 queries , Gzip On, Redis On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表