How can a unit test confirm an exception has been thrown

蓝咒 提交于 2020-01-12 03:16:53

问题


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?


回答1:


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.




回答2:


[ExpectedException(typeof(System.Exception))]

for Visual Studio Unit Testing Framework.

See 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.




回答3:


If you want to follow the triple-A pattern (arrange, act, assert), you could go for this, regardless of test framework:

[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"));
}



回答4:


If you are using Nunit, you can tag your test with

[ExpectedException( "System.ArgumentException" ) )]



回答5:


You can usee Verify() method for Unit Testing and compare your Exception Message from return type.

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

You need to write some classname or datatype in It.IsAny<> block



来源:https://stackoverflow.com/questions/6125143/how-can-a-unit-test-confirm-an-exception-has-been-thrown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!