Unit testing a multithreaded application?

后端 未结 9 2503
-上瘾入骨i
-上瘾入骨i 2020-11-28 06:03

Does anyone have any advice for a consistent way to unit test a multithreaded application? I have done one application where our mock \"worker threads\" had a thread.sleep

9条回答
  •  离开以前
    2020-11-28 06:50

    If you have to test that a background thread does something, a simple technique I find handy is to to have a WaitUntilTrue method, which looks something like this:

    bool WaitUntilTrue(Func func,
                  int timeoutInMillis,
                  int timeBetweenChecksMillis)
    {
        Stopwatch stopwatch = Stopwatch.StartNew();
    
        while(stopwatch.ElapsedMilliseconds < timeoutInMillis)
        {
            if (func())
                return true;
            Thread.Sleep(timeBetweenChecksMillis);
        }   
        return false;
    }
    

    Used like this:

    volatile bool backgroundThreadHasFinished = false;
    //run your multithreaded test and make sure the thread sets the above variable.
    
    Assert.IsTrue(WaitUntilTrue(x => backgroundThreadHasFinished, 1000, 10));
    

    This way you don't have to sleep your main testing thread for a long time to give the background thread time to finish. If the background doesn't finish in a reasonable amount of time, the test fails.

提交回复
热议问题