Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Unit Test an infinitely waiting listener?

I am using MSTest, Vs2010. I have a situation where a method with a while loop calls AutoResetEvent.WaitOne. I can trigger this event from my Test method; it will iterate one time and then again wait for this event to be triggered.

I am unable to assert anything in this situation. How can I Unit Test these kind of methods?

Thanks

like image 733
Devesh Avatar asked Oct 22 '22 05:10

Devesh


1 Answers

I would suggest using a Task in your unit test to initialise the loop in a separate thread.

public void TestMyLoop()
{

    var myLooper = new Looper();

    Task t = Task.Run(() => myLooper.BeginWorking());  // BeginWorking is an infinite loop, it will never end!

    myLooper.AddAnItemToProcess(new Item());

    Thread.Sleep(5000); // wait 5 seconds, alternatively hook into and `await` some completion event.

    // assert here
    Assert.That(myLooper.processedItems == 1);

 }
like image 161
NibblyPig Avatar answered Oct 29 '22 01:10

NibblyPig