What do I have to do so that assertions won't

2019-02-14 17:23发布

问题:

We run automated NUnit tests on our C# projects using hudson/jenkins on several virtual machines which run mostly unattended on some server. The tests involve starting several processes that exchange data, one of which is NUnit itself, the others created by the unit test.

Sometimes, one of the developer checks in something that triggers an assertion (Debug.Assert()). This then pops up a message box, asking the user what to do. Usually those happen in one of the "external" processes created by the unit tests. They will block that process while the other processes give up, because they can't communicate. However, due to the nature of the system, the next tests will all fail, too, as long as that one process is blocked waiting for someone to click away that message box.

I've been told that you can change the settings for a .NET program so that an assertion won't pop up a message box. Ideally, the process would just write something to stdout or stderr, for Jenkins to record.

So what do I have to do to turn off those interactive assertion dialogs?

回答1:

You need to implement System.Diagnostics.TraceListener that will not pop up dialog on Fail (i.e. you can report error to unit test framework) and add this listener instead of default one by using Listeners.Clear/Add

public class MyListenerThatDoesNotShowDialogOnFail: System.Diagnostics.TraceListener
{....
    public override void Fail(string message, string detailMessage)
    {// do soemthing UnitTest friendly here
    }

}

System.Diagnostics.Debug.Listeners.Clear();
System.Diagnostics.Debug.Listeners.Add(new MyListenerThatDoesNotShowDialogOnFail());

This code should be in your Unit test setup portion. This way regular debug build will show assert dialogs, but while running Unit tests it will do something sensible for the test (like Assert.Fail). Note that you should consider restoring original listeners in test's teardown methods.



回答2:

Do not test the Debug version of the library. You want to know what fails when it is running on the customer's machine, that will be the Release version. Automatically solves your problem with asserts.