try {somethingThatShouldThrowAnException();Assert.Fail(); // If it gets to this line, no exception was thrown} catch (GoodException) { }
正如@Jonas指出的那样,这对于捕获基本异常不起作用:
try {somethingThatShouldThrowAnException();Assert.Fail(); // raises AssertionException} catch (Exception) {// Catches the assertion exception, and the test passes}
[TestMethod][ExpectedException(typeof(ArgumentException),"A userId of null was inappropriately allowed.")]public void NullUserIdInConstructor(){LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");}
public static TException AssertThrows<TException>(Action action) where TException : Exception{try{action();}catch (TException ex){return ex;}Assert.Fail("Expected exception was not thrown");
return null;}
using System;using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace YourProject.Tests{public static class MyAssert{public static void Throws<T>( Action func ) where T : Exception{var exceptionThrown = false;try{func.Invoke();}catch ( T ){exceptionThrown = true;}
if ( !exceptionThrown ){throw new AssertFailedException(String.Format("An exception of type {0} was expected, but not thrown", typeof(T)));}}}}
/// <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.");}
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)));}}}}
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));}}
示例用途:
[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)}
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)));}}