My unit tests are built using Visual Studio 2017/19/MSTest.
I have a customized version of the ExpectedExceptionBaseAttribute that checks both the Exception thrown but also the Message to ensure it is the expected value. Using it looks like this:
Code:
[TestMethod]
[ExpectedExceptionMessage(typeof(InvalidOperationException), "This is the Message I expect.")]
public void MyUnitTest() { … }
All unit tests using this attribute are shown as failures by NCrunch. Could you please refactor your code to look for the ExpectedExceptionBaseAttribute rather than ExpectedExceptionAttribute? Thanks!
Here is the full source of my ExpectedExceptionMessageAttribute class:
Code:
/// <summary>
/// Ensures that a unit test throws the given exception and that the exception's message is a given value.
/// </summary>
public sealed class ExpectedExceptionMessageAttribute : ExpectedExceptionBaseAttribute
{
readonly string ExpectedExceptionMessage;
readonly Type ExpectedExceptionType;
/// <summary>
/// Initializes a new instance of <see cref="ExpectedExceptionMessageAttribute"/>.
/// </summary>
/// <param name="expectedExceptionType">The Type of the Exception the unit test should throw.</param>
/// <param name="expectedExceptionMessage">The expected value of the Message property of the Exception thrown.</param>
public ExpectedExceptionMessageAttribute(Type expectedExceptionType, string expectedExceptionMessage)
{
ExpectedExceptionType = expectedExceptionType;
ExpectedExceptionMessage = expectedExceptionMessage;
}
/// <summary>
/// Called when a unit test throws an unhandled exception.
/// </summary>
/// <param name="exception">The Exception that was thrown.</param>
protected override void Verify(Exception exception)
{
Assert.IsNotNull(exception);
// We're not interested in assertion failures in the test method
base.RethrowIfAssertException(exception);
// Make sure the exception thrown is of the expected type
Assert.IsInstanceOfType(exception, ExpectedExceptionType, "The exception thrown is the wrong type.");
// Make sure the exception's message matches
Assert.AreEqual(ExpectedExceptionMessage, exception.Message,
string.Format("{0}.Message was not expected value.", exception.GetType().Name));
}
}