Using the WPF Dispatcher in unit tests

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

    It's a bit old post, BeginInvoke is not a preferable option today. I was looking for a solution for mocking and had't found anything for InvokeAsync:

    await App.Current.Dispatcher.InvokeAsync(() => something );

    I've added new Class called Dispatcher, implementing IDispatcher, then inject into viewModel constructor:

    public class Dispatcher : IDispatcher
    {
        public async Task DispatchAsync(Action action)
        {
            await App.Current.Dispatcher.InvokeAsync(action);
        }
    }
    public interface IDispatcher
        {
            Task DispatchAsync(Action action);
        }
    

    Then in test I've injected MockDispatcher into viewModel in constructor:

    internal class MockDispatcher : IDispatcher
        {
            public async Task DispatchAsync(Action action)
            {
                await Task.Run(action);
            }
        }
    

    Use in the view model:

    await m_dispatcher.DispatchAsync(() => something);
    

提交回复
热议问题