Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delayed NUnit Assert message evaluation

Tags:

c#

nunit

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.

like image 873
mtijn Avatar asked Jan 14 '13 13:01

mtijn


2 Answers

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

like image 180
Evgeniy Mironov Avatar answered Sep 20 '22 12:09

Evgeniy Mironov


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.

like image 22
Martin Avatar answered Sep 18 '22 12:09

Martin