How to write unit test for Application.Current.Dispatcher.BeginInvoke

31 views Asked by At

I have a custom wpfmessagebox that has to be invoked from the dispatcher. It displays properly when running however I'm having trouble writing a unit test for it. The test can run but the "cVM.Returns(1).Show();" line fails.

Foo(bool someCondition)
{

if(someCondition)
{
  Application.Current.Dispatcher.BeginInvoke((Action)() =>
 {
   var customMB = _wpfMB.BuildCustomMessageBox();
   customMB.Show();
 }));
}
}

Unit Test

public void CustomMBTest()
{
 Application app = new Application();
 ICustomMessageBoxView cVM = Substitute.For<ICustomMessageBoxView>();
 CustomMssageBoxBuilder cMB = new CustomMssageBoxBuilder(cVM);
 WPFMessageBoxService.BuildCustomMessageBox.Returns(cMB);
 vm.Foo(true);
 DoEvents();
 cVM.Returns(1).Show();
}

public void DoEvents()
{
  DispatcherFrame frame = new DispatcherFrame();
  Application.Current.Dispatcher.Invoke( new DispatcherOperationCallback(ExitFrame), frame);
  Dispatcher.PushFrame(frame);
}

public object ExitFrame(object f)
{
  ((DispatcherFrame)f).Continue = false;
  return null;
}

While debugging I can see that it does hit customMB.Show() but it fails to receive in the test.

0

There are 0 answers