How should I unit test threaded code?

后端 未结 26 1360
悲&欢浪女
悲&欢浪女 2020-11-22 04:09

I have thus far avoided the nightmare that is testing multi-threaded code since it just seems like too much of a minefield. I\'d like to ask how people have gone about test

26条回答
  •  一生所求
    2020-11-22 04:43

    I handle unit tests of threaded components the same way I handle any unit test, that is, with inversion of control and isolation frameworks. I develop in the .Net-arena and, out of the box, the threading (among other things) is very hard (I'd say nearly impossible) to fully isolate.

    Therefore, I've written wrappers that looks something like this (simplified):

    public interface IThread
    {
        void Start();
        ...
    }
    
    public class ThreadWrapper : IThread
    {
        private readonly Thread _thread;
         
        public ThreadWrapper(ThreadStart threadStart)
        {
            _thread = new Thread(threadStart);
        }
    
        public Start()
        {
            _thread.Start();
        }
    }
        
    public interface IThreadingManager
    {
        IThread CreateThread(ThreadStart threadStart);
    }
    
    public class ThreadingManager : IThreadingManager
    {
        public IThread CreateThread(ThreadStart threadStart)
        {
             return new ThreadWrapper(threadStart)
        }
    }
    

    From there, I can easily inject the IThreadingManager into my components and use my isolation framework of choice to make the thread behave as I expect during the test.

    That has so far worked great for me, and I use the same approach for the thread pool, things in System.Environment, Sleep etc. etc.

提交回复
热议问题