Using the WPF Dispatcher in unit tests

前端 未结 16 2140
北恋
北恋 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:06

    I accomplished this by wrapping Dispatcher in my own IDispatcher interface, and then using Moq to verify the call to it was made.

    IDispatcher interface:

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

    Real dispatcher implementation:

    class RealDispatcher : IDispatcher
    {
        private readonly Dispatcher _dispatcher;
    
        public RealDispatcher(Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
        }
    
        public void BeginInvoke(Delegate method, params object[] args)
        {
            _dispatcher.BeginInvoke(method, args);
        }
    }
    

    Initializing dispatcher in your class under test:

    public ClassUnderTest(IDispatcher dispatcher = null)
    {
        _dispatcher = dispatcher ?? new UiDispatcher(Application.Current?.Dispatcher);
    }
    

    Mocking the dispatcher inside unit tests (in this case my event handler is OnMyEventHandler and accepts a single bool parameter called myBoolParameter)

    [Test]
    public void When_DoSomething_Then_InvokeMyEventHandler()
    {
        var dispatcher = new Mock();
    
        ClassUnderTest classUnderTest = new ClassUnderTest(dispatcher.Object);
    
        Action OnMyEventHanlder = delegate (bool myBoolParameter) { };
        classUnderTest.OnMyEvent += OnMyEventHanlder;
    
        classUnderTest.DoSomething();
    
        //verify that OnMyEventHandler is invoked with 'false' argument passed in
        dispatcher.Verify(p => p.BeginInvoke(OnMyEventHanlder, false), Times.Once);
    }
    

提交回复
热议问题