Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit-testing threads?

I just need to unit test some methods like this:

public void start()
{
    myThread.Start();
}

public void stop()
{
    myThread.Abort();
}

How can i do that? I may call start method and check for IsAlive==true but then thread keeps working in background and calls its own method. Another way is I call start and then stop immediately but it's not neat cause it would be like I'm testing two things. It's so simple but arghh!

like image 554
cartman Avatar asked Dec 15 '10 07:12

cartman


2 Answers

The trick is to separate the asynchronous behavior from your logic. Observe that your actual logic is synchronous, and that the asynchronous part is simply some "waiting time" in between.

The book xUnit Test Patterns describes it well. It's even a pattern - Humble Object. It's explained there way better than I can.

like image 142
Mike Avatar answered Sep 22 '22 22:09

Mike


Use thread synchronization and wait handles to wait on running threads.

Thread Synchronization (C# Programming Guide)

like image 21
decyclone Avatar answered Sep 19 '22 22:09

decyclone