为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用Assert验证是否已引发异常?

如何使用Assert验证是否已引发异常?

回首忆惘然 2020-02-03 15:05:55
如何使用Assert(或其他Test类?)来验证是否已引发异常?
查看完整描述

3 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

对于“ Visual Studio Team Test”,您似乎将ExpectedException属性应用于该测试的方法。


这里的文档样本:使用Visual Studio Team Test进行单元测试的演练


[TestMethod]

[ExpectedException(typeof(ArgumentException),

    "A userId of null was inappropriately allowed.")]

public void NullUserIdInConstructor()

{

   LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");

}


查看完整回答
反对 回复 2020-02-03
?
婷婷同学_

TA贡献1844条经验 获得超8个赞

实现此目的的首选方法是编写一个称为Throws的方法,并像其他任何Assert方法一样使用它。不幸的是,.NET不允许您编写静态扩展方法,因此您无法像使用该方法实际上属于Assert类中的内部版本一样使用此方法。只需创建另一个名为MyAssert或类似名称的文件即可。该类如下所示:


using System;

using Microsoft.VisualStudio.TestTools.UnitTesting;


namespace YourProject.Tests

{

    public static class MyAssert

    {

        public static void Throws<T>( Action func ) where T : Exception

        {

            var exceptionThrown = false;

            try

            {

                func.Invoke();

            }

            catch ( T )

            {

                exceptionThrown = true;

            }


            if ( !exceptionThrown )

            {

                throw new AssertFailedException(

                    String.Format("An exception of type {0} was expected, but not thrown", typeof(T))

                    );

            }

        }

    }

}

这意味着您的单元测试如下所示:


[TestMethod()]

public void ExceptionTest()

{

    String testStr = null;

    MyAssert.Throws<NullReferenceException>(() => testStr.ToUpper());

}

它的外观和行为更像其余的单元测试语法。


查看完整回答
反对 回复 2020-02-03
  • 3 回答
  • 0 关注
  • 2409 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信