如何单元测试确认异常被抛出 [英] How can a unit test confirm an exception has been thrown

查看:631
本文介绍了如何单元测试确认异常被抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写单元测试C#类,我的一个测试,应引起法当数据被添加到抛出异常。我如何使用我的单元测试,以确认该异常被抛出?

Im writing a unit test for a c# class, One of my tests should cause the method to throw an exception when the data is added. How can i use my unit test to confirm that the exception has been thrown?

推荐答案

这要看是什么单元测试框架,您使用。在所有的情况下,你可以这样做:

It depends on what unit test framework you're using. In all cases you could do something like:

[Test]
public void MakeItGoBang()
{
     Foo foo = new Foo();
     try
     {
         foo.Bang();
         Assert.Fail("Expected exception");
     }
     catch (BangException)
     { 
         // Expected
     }
}

在一些框架有一个属性,你可以添加到测试方法EX preSS预期的异常,或有可能是一种方法,如:

In some frameworks there's an attribute you can add to the test method to express the expected exception, or there may be a method, such as:

[Test]
public void MakeItGoBang()
{
     Foo foo = new Foo();
     Assert.Throws<BangException>(() => foo.Bang());
}

这是更好的限制这样的范围内,因为如果你把它应用到整个测试,测试可能通过,即使在错误的行抛出异常。

这篇关于如何单元测试确认异常被抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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