Question

Is there a way to specify a message for Assert.AreEqual(object, object, string) that combines the custom message with the default message?

I have the following code:

foreach (var testCase in testCases)
{
    Assert.AreEqual(testCase.Value, myObj.myMethod(testCase.Key), combinedMessage);
}

I would like to specify the test case key in addition to the example message from the VS unit testing framework below:

Assert.AreEqual failed. Expected:<True>. Actual:<False>.

Perhaps something like Failed on the following test case: AB.

Was it helpful?

Solution

The overload will do this for you automatically. As a test I made this test method to see what the output would be:

    [TestMethod]
    public void Test()
    {
        Assert.AreEqual(true, false, "Failed on the following test case: AB");
    }

And the Error Message output was: Assert.AreEqual failed. Expected:<True>. Actual:<False>. Failed on the following test case: AB

The message parameter is already appended/combined to the default message.

For your case if you just want to get the test key the test could look like:

foreach (var testCase in testCases)
{
    Assert.AreEqual(testCase.Value, myObj.myMethod(testCase.Key), 
        "Failed on the following test case: " + testCase.Key.ToString());
}

And if the test cases should each have their own custom message, it would then make sense to move the custom error message to the testCase class. As part of the creation of each of the objects you could specify those three properties then:

testCase.Value = true;
testCase.Key = "AB";
testCase.FailureMessage = "Failed on the following test case: AB";

This type of structure would allow for having a specified message to be appended for every instance of testCase. Doing so would allow the unit test to look like this:

foreach (var testCase in testCases)
{
    Assert.AreEqual(testCase.Value, myObj.myMethod(testCase.Key), 
        testCase.FailureMessage));
}

and the output in your example appears as: Assert.AreEqual failed. Expected:<True>. Actual:<False>. Failed on the following test case: AB

OTHER TIPS

Could you not just concat the message?

foreach (var testCase in testCases)
{
    string message = string.Format("{0}: {1}", defaultMessage, testCase.Key);
    Assert.AreEqual(testCase.Value, myObj.myMethod(testCase.Key), message );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top