Delayed NUnit Assert message evaluation

青春壹個敷衍的年華 提交于 2019-12-21 08:08:25

问题


I have this assert in my test code

Assert.That(() => eventData.Count == 0,
Is.True.After(notificationPollingDelay),
"Received unexpected event with last event data" + eventData.Last().Description());

that asserts some condition after a period of time and on failure produces a message. it fails to run because the message string is constructed when the assert starts and not when the assert ends. therefore the eventData collection is still empty (as it is initially) and the attempt to get the Description of the last item in the collection fails. is there a workaround or decent alternative to this in NUnit or do I have to revert to using Thread.Sleep in my tests?

PS: I'm using NUnit 2.5.10.


回答1:


You may use this scheme:

var constrain = Is.True.After(notificationPollingDelay);
var condition = constrain.Matches(() => eventData.Count == 0);
Assert.IsTrue(condition, 
              "Received unexpected event with last event data" + 
              eventData.Last().Description());

This method is similar to the use Thread.Sleep




回答2:


In NUnit version 3.50 I had to use a different syntax. Here is the example:

var constraint = Is.True.After( delayInMilliseconds: 100000, pollingInterval: 100);
Assert.That( () => yourCondition, constraint );


This will test whether yourCondition is true waiting a certain maximum time using the DelayedConstraint created by the Is.True.After method.

In this example the DelayedConstraint is configured to use maximum time of 100 seconds polling every 0.1 seconds.

See aslo the legacy NUnit 2.5 documentation for DelayedConstraint.




回答3:


The simplest answer is "don't include that text in your failure message". I personally almost never include a failure message; if your test is atomic enough you don't need to do it. Usually if I need to figure out a cryptic failure, only a debugger helps anyway.

If you really want to do it, this code should work without managing the threads yourself.

try
{
    Assert.That(() => eventData.Count == 0, Is.True.After(notificationPollingDelay));
}
catch(AssertionException)
{
    throw new Exception("Received unexpected event with last event data" + eventData.Last().Description());
}


来源:https://stackoverflow.com/questions/14319435/delayed-nunit-assert-message-evaluation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!