Question

I created a custom Assert class for unit testing, and I'm not sure what to do when I want to notify that the test has failed:

public static class MyAssert
{
    public static void Contains(File file, string text){
        if(!ContainText(file, text)){
            // what to do here?
        }
    }
}

I reflected the Microsoft.VisualStudio.TestTools.UnitTesting.Assert Class and noticed that it calls HandleFail:

internal static void HandleFail(string assertionName, string message, params object[] parameters)
{
  string str = string.Empty;
  if (!string.IsNullOrEmpty(message))
    str = parameters != null ? string.Format((IFormatProvider) CultureInfo.CurrentCulture, Assert.ReplaceNulls((object) message), parameters) : Assert.ReplaceNulls((object) message);
  if (Assert.AssertionFailure != null)
    Assert.AssertionFailure((object) null, EventArgs.Empty);
  throw new AssertFailedException((string) FrameworkMessages.AssertionFailed((object) assertionName, (object) str));
}

But this is an internal method. I could use reflection to call it, or maybe it makes more sense to throw an AssertFailedException? Is there another option that I'm missing?

Was it helpful?

Solution

In order to make a custom Assert method as operate exactly like the standard assert methods, you must throw a new AssertFailedException. At first I really didn't like this because the debugger stops on the AssertFailedException throw statement, and not on the actual assert statement. After a little more research I discovered the DebuggerHidden method attribute and viola, my assert performs as desired.

[DebuggerHidden]
public static void Contains(File file, string text){
    if(!ContainText(file, text)){
        HandleFail("MyAssert.Contains", null, null);
    }
}

[DebuggerHidden]
private static void HandleFail(string assertName, string message, params object[] parameters )
{
    message = message ?? String.Empty;
    if (parameters == null)
    {
        throw new AssertFailedException(String.Format("{0} failed. {1}", assertName, message));
    }
    else
    {
        throw new AssertFailedException(String.Format("{0} failed. {1}", assertName, String.Format(message, parameters)));
    }
}

OTHER TIPS

Just call a standard Assert from inside your custom one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top