Using the WPF Dispatcher in unit tests

前端 未结 16 2131
北恋
北恋 2020-11-27 02:48

I\'m having trouble getting the Dispatcher to run a delegate I\'m passing to it when unit testing. Everything works fine when I\'m running the program, but, during a unit te

16条回答
  •  醉梦人生
    2020-11-27 03:17

    We've solved this issue by simply mocking out the dispatcher behind an interface, and pulling in the interface from our IOC container. Here's the interface:

    public interface IDispatcher
    {
        void Dispatch( Delegate method, params object[] args );
    }
    

    Here's the concrete implementation registered in the IOC container for the real app

    [Export(typeof(IDispatcher))]
    public class ApplicationDispatcher : IDispatcher
    {
        public void Dispatch( Delegate method, params object[] args )
        { UnderlyingDispatcher.BeginInvoke(method, args); }
    
        // -----
    
        Dispatcher UnderlyingDispatcher
        {
            get
            {
                if( App.Current == null )
                    throw new InvalidOperationException("You must call this method from within a running WPF application!");
    
                if( App.Current.Dispatcher == null )
                    throw new InvalidOperationException("You must call this method from within a running WPF application with an active dispatcher!");
    
                return App.Current.Dispatcher;
            }
        }
    }
    

    And here's a mock one that we supply to the code during unit tests:

    public class MockDispatcher : IDispatcher
    {
        public void Dispatch(Delegate method, params object[] args)
        { method.DynamicInvoke(args); }
    }
    

    We also have a variant of the MockDispatcher which executes delegates in a background thread, but it's not neccessary most of the time

提交回复
热议问题