ThreadTester with new Ability: StopWhenTrue() and thread polling

By Roy Osherove In Agile, Tips & Tricks, Unit Testing

Markdown version

Historical article · Originally published June 25, 2007; technical details may be outdated.

I've updated The ThreadTester Library with a new ability: StopWhenTrue().

It allows you to periodically poll while all the threads are running (and the test is blocking) and either assert stuff or stop the run midway when some condition is true. 

Here's a test that shows how this is possible with the new API:

[Test]
public void StopWhenTrue_ReturnTrueWhenCountOver1000_AllThreadsStopImmediately()
{
 Counter c = new Counter();
 ThreadTester tt = new ThreadTester();
 tt.RunBehavior=ThreadRunBehavior.RunForSpecificTime;
 tt.AddThreadAction(delegate
             {
                for (int j = 0; j < 103; j++)
                  {
                                               c.Increment();
                                           }
                                           Thread.Sleep(50);
                                       });
 
 tt.StopWhenTrue(delegate
                  {
                    // you can also assert stuff here
                    Console.WriteLine("currently at " + c.Count);
                     return c.Count > 1000;
                  },100);// check every 100ms
 
          //this test will end in less than a second because of our added functionality
tt.StartAllThreads(10000); 
 Assert.Greater(c.Count,1000);
 Assert.Less(c.Count,1050);
}

More in Agile

All posts in Agile