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
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);
}