开发者

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 d开发者_如何学Pythonata 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
     }
}

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.


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


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


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

[ExpectedException( "System.ArgumentException" ) )]


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜