开发者

NUnit: Execute code upon assertion failure hook

Is there a hook in NUnit to execute code only when assertion fails without catching the exception itself. Basically, it should accept action delegate to be executed when assertion fails and then re-throw exception. Why do I need this? I need to compare two objects and dump the result on the screen, for easier debugging, when assertion fails.

Something like this works but is a bad hack, The problem is that it eagerly evaluates ProcessCompareError so I开发者_如何学运维 have unnecessary overhead, plus it does it no matter if there is an error or not. So, is there overload that will accept the delegate that would be executed when assertion fails?

Assert.That(benefitLimitComparer.Compare(copyBenefitLimit, origBenefitLimit), Is.EqualTo(0),limitError, ProcessCompareError(origBenefitLimit, copyBenefitLimit));
                }
            }
        }

        private string ProcessCompareError(BenefitLimit origBenefitLimit, BenefitLimit copyBenefitLimit)
        {        
            Console.WriteLine("Original: ");
            ObjectDumper.Write(origBenefitLimit);
            Console.WriteLine("Copy");
            ObjectDumper.Write(copyBenefitLimit);

            return "";
        }


I'm not sure how it might be done through a delegate. One alternative is to store the result of the Compare. If the result is false, write out the contents of the objects and then call Assert.Fail()


There is a possibilty to wrap an assert as an Action in a try-catch. In the catch you can handle the additional compare:

    public static void ExecuteAssert(Action assert)
    {
        if (assert == null) return;
        try
        {
            assert();
        }
        catch (Exception ex)
        {
            // perform the compare
        }
    }

As remark: I use a similar method to continue test execution and avoid the entire test to stop, if some non-fatal checks fail. Actually I iterate through a number of actions:

private static void VerifyAll(params Action[] asserts)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜