unit testing如何确认exception已被抛出

我正在为ac#class编写unit testing,我的一个测试应该导致该方法在添加数据时抛出exception。 我如何使用unit testing来确认是否抛出了exception?

这取决于您正在使用的unit testing框架。 在所有情况下,您可以执行以下操作:

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

在某些框架中,您可以添加一个属性来测试方法来表达预期的exception,或者可能有一个方法,例如:

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

像这样限制范围更好,就像你将它应用于整个测试一样,即使错误的行抛出exception,测试也可以通过。

 [ExpectedException(typeof(System.Exception))] 

用于Visual Studiounit testing框架。

请参阅MSDN :

如果抛出预期的exception,测试方法将通过。

如果抛出的exceptioninheritance自预期的exception,则测试将失败。

如果你想遵循三A模式(安排,行动,断言),无论测试框架如何,你都可以这样做:

 [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()); Assert.That(caughtException.Message, Is.EqualTo("My Error Message")); } 

如果您使用的是Nunit,则可以标记您的测试

 [ExpectedException( "System.ArgumentException" ) )] 

您可以使用Verify()方法进行unit testing,并从返回类型中比较您的exception消息。

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

您需要在It.IsAny <>块中编写一些类名或数据类型