johnsondl1
johnsondl1

Reputation: 83

Custom Assertions with MSTest - Handling the AssertFailedException

I would like to provide some custom Assert methods in my MSTest Unit Testing framework. I have my own static class "CustomAssert", and methods like the one below:

public static void DatesAreEqualToDay(DateTime expectedValue, DateTime actualValue)
{
    if (!(
       expectedValue.Year == actualValue.Year &&
       expectedValue.Month == actualValue.Month &&
        expectedValue.Day == actualValue.Day))
    {
        Assert.Fail(string.Format("Expected: <{0:yyyy-MM-dd}> - Actual <{1:yyyy-MM-dd}>", expectedValue, actualValue));
    }
}

The test fails when the the dates are not the same. But instead the custom error message, I am just getting the message that the test threw an AssertFailedException. How do you get the custom assertions to be handled like MSTest's Assert methods, and show the intelligent error message?

Upvotes: 1

Views: 1750

Answers (2)

Martin
Martin

Reputation: 40

Instead of creating your own custom assertions, you could also try to use one of the frameworks that are currently available. Like for example: Fluent Assertions.

Upvotes: 1

johnsondl1
johnsondl1

Reputation: 83

This issue was caused because my "TestFramework" project was referencing the VS2008 version of the Microsoft.VisualStudio.QualityTools.UnitTesting assembly. I changed the reference to the VS2010 version of the assembly, and the custom assertions started behaving as expected, MSTest displayed the custom assert message, rather than the "AssertFailedException".

Upvotes: 0

Related Questions