June 30, 2013

Code Contract


This is a code contract type class that can make code assertions without throwing an Assert dialog during an NUnit test:
public static class CodeContract
{
    private static bool runningFromNUnit = false;

    static CodeContract()
    {
        runningFromNUnit = AppDomain.CurrentDomain.GetAssemblies().Any(a => 
               a.FullName.ToLowerInvariant().StartsWith("nunit.framework"));
    }

    private static bool IsRunningFromNUnit
    {
        get { return runningFromNUnit; }
    }

    private static bool UseAssert()
    {
        return ForceAssertOnError ||
            (Debugger.IsAttached && !IsRunningFromNUnit);
    }

    public static bool ForceAssertOnError
    {
        get;
        set;
    }

    public static void Requires(bool condition,
            string message = "", string extraInfo = "")
    {
        if (!condition)
        {
            string failType = "Contract requirement failure detected: ";
            Trace.TraceError(failType + message + extraInfo);
            if (UseAssert())
            {
                Debug.Assert(false, failType + message, extraInfo);
            }
        }
    }

    public static void RequiresArgument(bool condition, string paramName,
            string extraInfo = "")
    {
        if (!condition)
        {
            string failType = "Argument requirement failure detected: ";
            Trace.TraceError(failType + paramName + extraInfo);
            if (UseAssert())
            {
                Debug.Assert(false, failType + paramName, extraInfo);
            }
            throw new ArgumentException(extraInfo, paramName);
        }
    }

    public static void RequiresArgumentNotNull(object parameter, string paramName,
        string extraInfo = "")
    {
        if (parameter == null)
        {
            string failType = "Argument not null requirement failure detected: ";
            Trace.TraceError(failType + paramName + extraInfo);
            if (UseAssert())
            {
                Debug.Assert(false, failType + paramName, extraInfo);
            }
            throw new ArgumentNullException(extraInfo, paramName);
        }
    }

}

No comments: