mardi 3 mars 2015

How to unit test code that suspends its execution without abstracting it out?

I have to unit test a method that suspends its execution (does some work periodically):



void m() {
do {
doSomeWork();
Thread.sleep(1000);
} while (condition);
}


What I have to test is multiple while loop execution and check if the doSomeWork() has been done correctly. So currently my test looks like this:


1) start execution of m() in a new thread.


2) in the main thread: Thread.sleep(1000 + 200);


3) in the main thread assert that the work has been done correctly.


4) in the main thread: Thread.sleep(1000 + 200);


5) in the main thread assert that the work has been done correctly.


6) and one more time 4 and 5


The problem is that the doSomeWork() on different machines takes different amount of time and its hard to find a good value to wait in the test.


I have seen a common approach to such situation is to abstract out the sleeping time and in test code don't wait: C# Unit Testing - Thread.Sleep(x) - How to Mock the System Clock


But I really have to verify that the implementation is waiting.


Do you have any suggestions how to write a robust unit test code for such scenario? It can also involve refactoring of the m() method.


Aucun commentaire:

Enregistrer un commentaire