如何单元测试确认异常被抛出抛出、单元测试、异常

2023-09-03 11:15:42 作者:顾念你

我写单元测试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());
}

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