简体   繁体   English

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

[英]How can a unit test confirm an exception has been thrown

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.我正在为 c# class 编写单元测试,我的一个测试应该导致该方法在添加数据时引发异常。 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
     }
}

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's nicer to limit the scope like this, as if you apply it to the whole test, the test could pass even if the wrong line threw the exception.最好像这样限制scope,就好像你把它应用到整个测试中一样,即使错误的行抛出异常,测试也可以通过。

[ExpectedException(typeof(System.Exception))]

for Visual Studio Unit Testing Framework.用于 Visual Studio 单元测试框架。

See MSDN :MSDN

The test method will pass if the expected exception is thrown.如果抛出预期的异常,测试方法将通过。

The test will fail if the thrown exception inherits from the expected exception.如果抛出的异常继承自预期的异常,则测试将失败。

If you want to follow the triple-A pattern (arrange, act, assert), you could go for this, regardless of test framework:如果您想遵循 AAA 模式(安排、行动、断言),则可以为此使用 go,而不管测试框架如何:

[Test]
public void MyMethod_DodgyStuffDone_ThrowsRulesException() {

    // arrange
    var myObject = CreateObject();
    Exception caughtException = null;

    // act
    try {
        myObject.DoDodgyStuff();
    }
    catch (Exception ex) {
        caughtException = ex;
    }

    // assert
    Assert.That(caughtException, Is.Not.Null);
    Assert.That(caughtException, Is.TypeOf<RulesException>());
    Assert.That(caughtException.Message, Is.EqualTo("My Error Message"));
}

If you are using Nunit, you can tag your test with如果您使用的是 Nunit,您可以使用

[ExpectedException( "System.ArgumentException" ) )]

You can usee Verify() method for Unit Testing and compare your Exception Message from return type.您可以使用 Verify() 方法进行单元测试,并从返回类型比较您的异常消息。

InterfaceMockObject.Verify(i =>i.Method(It.IsAny<>())), "Your received Exception Message");

You need to write some classname or datatype in It.IsAny<> block您需要在 It.IsAny<> 块中编写一些类名或数据类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM