While an ExpectedException cannot be used as-to to check an exception message, you can implement your own exception-checking logic by inheriting from ExpectedExceptionBaseAttribute :
Introducing your own expected exception check. you can specify additional information and requirements that the built-in methods of the ExpectedExceptionAttribute class cannot be processed, for example, the following:
- Check exception status.
- Waiting for more than one type of exception.
- Displays a custom message when an incorrect exception type occurs.
- Negative test result control.
In your case, it might look something like this:
public sealed class ExpectedExceptionMessageAttribute<T> : ExpectedExceptionBaseAttribute { readonly string _expectedMessage; public ExpectedExceptionMessageAttribute(string expectedMessage) { _expectedMessage = expectedMessage; } protected override void Verify(System.Exception exception) {
HAving said that I would still be inclined to use the direct try - catch approach, although, more specifically, where exactly is the exception exception expected:
public static void Throws<T>(Action action, Predicate<T> predicate = null) where T : Exception { try { action(); } catch (T e) { if (predicate == null || predicate(e)) { return; } Assert.Fail($"Exception of type {typeof(T)} thrown as expected, but the provided predicate rejected it: {e}"); } catch (Exception e) { Assert.Fail($"Expected exception of type {typeof(T)} but a different exception was thrown: {e}"); } Assert.Fail($"No exception thrown, expected {typeof(T)}"); }
source share