如何使用Assert(或其余Test类?)来验证是否抛出了异常? html
好吧,我几乎能够总结一下以前全部其余人所说的内容......不管如何,这里是我根据好的答案创建的代码:)剩下要作的就是复制和使用...... 框架
/// <summary> /// Checks to make sure that the input delegate throws a exception of type TException. /// </summary> /// <typeparam name="TException">The type of exception expected.</typeparam> /// <param name="methodToExecute">The method to execute to generate the exception.</param> public static void AssertRaises<TException>(Action methodToExecute) where TException : System.Exception { try { methodToExecute(); } catch (TException) { return; } catch (System.Exception ex) { Assert.Fail("Expected exception of type " + typeof(TException) + " but type of " + ex.GetType() + " was thrown instead."); } Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown."); }
@Richiban上面提供的帮助程序工做得很好,除了它不处理抛出异常的状况,但不处理预期的类型。 如下内容涉及: 测试
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace YourProject.Tests { public static class MyAssert { /// <summary> /// Helper for Asserting that a function throws an exception of a particular type. /// </summary> public static void Throws<T>( Action func ) where T : Exception { Exception exceptionOther = null; var exceptionThrown = false; try { func.Invoke(); } catch ( T ) { exceptionThrown = true; } catch (Exception e) { exceptionOther = e; } if ( !exceptionThrown ) { if (exceptionOther != null) { throw new AssertFailedException( String.Format("An exception of type {0} was expected, but not thrown. Instead, an exception of type {1} was thrown.", typeof(T), exceptionOther.GetType()), exceptionOther ); } throw new AssertFailedException( String.Format("An exception of type {0} was expected, but no exception was thrown.", typeof(T)) ); } } } }
若是你使用NUNIT,你能够这样作: spa
Assert.Throws<ExpectedException>(() => methodToTest());
还能够存储抛出的异常以进一步验证它: 设计
ExpectedException ex = Assert.Throws<ExpectedException>(() => methodToTest()); Assert.AreEqual( "Expected message text.", ex.Message ); Assert.AreEqual( 5, ex.SomeNumber);
请参阅: http : //nunit.org/docs/2.5/exceptionAsserts.html code
我不建议使用ExpectedException属性(由于它过于约束和容易出错)或者在每一个测试中编写一个try / catch块(由于它太复杂且容易出错)。 使用设计良好的断言方法 - 由测试框架提供或编写本身的方法。 这是我写的和使用的。 orm
public static class ExceptionAssert { private static T GetException<T>(Action action, string message="") where T : Exception { try { action(); } catch (T exception) { return exception; } throw new AssertFailedException("Expected exception " + typeof(T).FullName + ", but none was propagated. " + message); } public static void Propagates<T>(Action action) where T : Exception { Propagates<T>(action, ""); } public static void Propagates<T>(Action action, string message) where T : Exception { GetException<T>(action, message); } public static void Propagates<T>(Action action, Action<T> validation) where T : Exception { Propagates(action, validation, ""); } public static void Propagates<T>(Action action, Action<T> validation, string message) where T : Exception { validation(GetException<T>(action, message)); } }
示例用途: htm
[TestMethod] public void Run_PropagatesWin32Exception_ForInvalidExeFile() { (test setup that might propagate Win32Exception) ExceptionAssert.Propagates<Win32Exception>( () => CommandExecutionUtil.Run(Assembly.GetExecutingAssembly().Location, new string[0])); (more asserts or something) } [TestMethod] public void Run_PropagatesFileNotFoundException_ForExecutableNotFound() { (test setup that might propagate FileNotFoundException) ExceptionAssert.Propagates<FileNotFoundException>( () => CommandExecutionUtil.Run("NotThere.exe", new string[0]), e => StringAssert.Contains(e.Message, "NotThere.exe")); (more asserts or something) }
笔记 blog
返回异常而不是支持验证回调是一个合理的想法,除了这样作使得这个断言的调用语法与我使用的其余断言很是不一样。 继承
与其余人不一样,我使用'propagates'而不是'throws',由于咱们只能测试异常是否从调用传播。 咱们没法直接测试抛出异常。 可是我想你能够将投射图像意味着:抛出而不是被抓住。
最后的想法
在切换到这种方法以前,我考虑使用ExpectedException属性,当测试仅验证异常类型并使用try / catch块时,若是须要更多验证。 可是,我不只要考虑每种测试使用哪一种技术,并且在须要改变时将代码从一种技术改成另外一种技术并非一件容易的事。 使用一致的方法能够节省精力。
总而言之,这种方法运动:易用性,灵活性和稳健性(很难作错)。
您可使用如下命令从Nuget下载程序包: PM> Install-Package MSTestExtensions ,它将nUnit / xUnit样式的Assert.Throws()语法添加到MsTest。
高级指令:下载程序集并从BaseTest继承,您可使用Assert.Throws()语法。
Throws实现的主要方法以下:
public static void Throws<T>(Action task, string expectedMessage, ExceptionMessageCompareOptions options) where T : Exception { try { task(); } catch (Exception ex) { AssertExceptionType<T>(ex); AssertExceptionMessage(ex, expectedMessage, options); return; } if (typeof(T).Equals(new Exception().GetType())) { Assert.Fail("Expected exception but no exception was thrown."); } else { Assert.Fail(string.Format("Expected exception of type {0} but no exception was thrown.", typeof(T))); } }
披露:我把这个包放在一块儿。
更多信息: http : //www.bradoncode.com/blog/2012/01/asserting-exceptions-in-mstest-with.html