public static void ExpectComException(ExceptionableAction action, params HRESULT[] expectedErrorCodes) { // Throw the ArgumentException if action is null. Don't want this to get caught in our try block. Verify.IsNotNull(action, "action"); foreach (HRESULT expectedErrorCode in expectedErrorCodes) { Assert.IsFalse(expectedErrorCode.Succeeded); } try { action(); } catch (COMException e) { // Only catch this if it maps to the expected HRESULT. foreach (HRESULT expectedErrorCode in expectedErrorCodes) { if (expectedErrorCode.Equals(e)) { return; } } // Caught the expected exception type. // If code past the catch block gets executed then the action didn't throw. throw; } throw new Exception("Expected a COMException to be thrown but the operation completed without raising one."); }
public static void ExpectException <TException>(ExceptionableAction action, bool supportSubclasses) where TException : Exception { // Throw the ArgumentException if action is null. Don't want this to get caught in our try block. try { action(); } catch (TException e) { // If the caller specified that they want exactly the TException type thrown then don't accept derived exceptions. if (!supportSubclasses && (e.GetType() != typeof(TException))) { throw; } // Caught the expected exception type. // If code past the catch block gets executed then the action didn't throw. return; } throw new Exception( string.Format("Expected an exception of type {0}{1} to be thrown but the operation completed without raising one.", typeof(TException).ToString(), supportSubclasses ? " (or a derived exception type)" : "")); }
public static void ExpectException <TException>(ExceptionableAction action) where TException : Exception { ExpectException <TException>(action, true); }