Using the WPF Dispatcher in unit tests
Asked Answered
H

16

54

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 test the following code will not run:

this.Dispatcher.BeginInvoke(new ThreadStart(delegate
{
    this.Users.Clear();

    foreach (User user in e.Results)
    {
        this.Users.Add(user);
    }
}), DispatcherPriority.Normal, null);

I have this code in my viewmodel base class to get a Dispatcher:

if (Application.Current != null)
{
    this.Dispatcher = Application.Current.Dispatcher;
}
else
{
    this.Dispatcher = Dispatcher.CurrentDispatcher;
}

Is there something I need to do to initialise the Dispatcher for unit tests? The Dispatcher never runs the code in the delegate.

Himyarite answered 9/7, 2009 at 23:1 Comment(2)
I get no error. Just what is passed to BeginInvoke on the Dispatcher never runs.Himyarite
I'll be honest and say I've not had to unit test a view model that utilizes a dispatcher yet. Is it possible the dispatcher isn't running. Would calling Dispatcher.CurrentDispatcher.Run() in your test help? I'm curious, so post results if you get them.Uncover
J
93

By using the Visual Studio Unit Test Framework you don’t need to initialize the Dispatcher yourself. You are absolutely right, that the Dispatcher doesn’t automatically process its queue.

You can write a simple helper method “DispatcherUtil.DoEvents()” which tells the Dispatcher to process its queue.

C# Code:

public static class DispatcherUtil
{
    [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
    public static void DoEvents()
    {
        DispatcherFrame frame = new DispatcherFrame();
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
            new DispatcherOperationCallback(ExitFrame), frame);
        Dispatcher.PushFrame(frame);
    }

    private static object ExitFrame(object frame)
    {
        ((DispatcherFrame)frame).Continue = false;
        return null;
    }
}

You find this class too in the WPF Application Framework (WAF).

Jecon answered 3/10, 2009 at 10:12 Comment(6)
I prefer this answer to the accepted answer, as this solution can run in a sequentially-authored test case, whereas the accepted answer requires that the test code is written in a callback-oriented approach.Trueman
This isn't working for me unfortunately. This method is also documented here for those interested: MSDN DispatcherFrame 'DoEvents' ExampleMeritocracy
Ignore my last comments - it works fine and is a good workaround to this common issue when testing WPF view models.Meritocracy
Am I right that this method shoud be called every time a system under test have to deal with Dispatcher? Or this method has to be called only once per unit-test session?Sideling
Your DoEvents will risk executing invokes that were scheduled by other unit tests, resulting in failures which are very difficult to debug :-( I found this post because somebody added a verbatim copy of the DispatcherUtil sample code to our unit tests and caused that very issue. I believe that hiding the dispatcher behind an interface as suggested by @OrionEdwards is a better approach, though I would use an implementation with an actual queue and a method for explicit dequeuing in the unit tests. If I get around to implementing it I'll add or edit an answer here.Astronomer
It's worth noting that requiring a real dispatcher is a bit of a red flag. Your unit tests should be testing each part of your code in isolation, and mocking up all other elements. @Orion's answer is more inline with correct unit testing best practices. You shouldn't need to use a real dispatcher in your unit tests, for the same reason you wouldn't use a real database connection, real http requests, etc.Copaiba
T
25

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

Tuantuareg answered 14/10, 2009 at 22:21 Comment(3)
how to mock DispatcherInvoke method?Teillo
@lukaszk, depending on your mocking framework, you would setup the Invoke method on your mock to actually run the delegate passed into it (if that were the behaviour that you require). You don't necessarily need to run that delegate, I have some tests where I just verify that the correct delegate was passed to the mock.Copaiba
For those using Moq, here is what worked for me: ` var mockDispatcher = new Mock<IDispatcher>(); mockDispatcher.Setup(dispatcher => dispatcher.Invoke(It.IsAny<Action>())).Callback<Action>(action => action());`Jade
L
17

You can unit test using a dispatcher, you just need to use the DispatcherFrame. Here is an example of one of my unit tests that uses the DispatcherFrame to force the dispatcher queue to execute.

[TestMethod]
public void DomainCollection_AddDomainObjectFromWorkerThread()
{
 Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
 DispatcherFrame frame = new DispatcherFrame();
 IDomainCollectionMetaData domainCollectionMetaData = this.GenerateIDomainCollectionMetaData();
 IDomainObject parentDomainObject = MockRepository.GenerateMock<IDomainObject>();
 DomainCollection sut = new DomainCollection(dispatcher, domainCollectionMetaData, parentDomainObject);

 IDomainObject domainObject = MockRepository.GenerateMock<IDomainObject>();

 sut.SetAsLoaded();
 bool raisedCollectionChanged = false;
 sut.ObservableCollection.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e)
 {
  raisedCollectionChanged = true;
  Assert.IsTrue(e.Action == NotifyCollectionChangedAction.Add, "The action was not add.");
  Assert.IsTrue(e.NewStartingIndex == 0, "NewStartingIndex was not 0.");
  Assert.IsTrue(e.NewItems[0] == domainObject, "NewItems not include added domain object.");
  Assert.IsTrue(e.OldItems == null, "OldItems was not null.");
  Assert.IsTrue(e.OldStartingIndex == -1, "OldStartingIndex was not -1.");
  frame.Continue = false;
 };

 WorkerDelegate worker = new WorkerDelegate(delegate(DomainCollection domainCollection)
  {
   domainCollection.Add(domainObject);
  });
 IAsyncResult ar = worker.BeginInvoke(sut, null, null);
 worker.EndInvoke(ar);
 Dispatcher.PushFrame(frame);
 Assert.IsTrue(raisedCollectionChanged, "CollectionChanged event not raised.");
}

I found out about it here.

Landowner answered 17/9, 2009 at 12:5 Comment(1)
Yeah, just came back to update this question with how I did it in the end. I read the same post I think!Himyarite
P
6

I solved this problem by creating a new Application in my unit test setup.

Then any class under test which access to Application.Current.Dispatcher will find a dispatcher.

Because only one Application is allowed in an AppDomain I used the AssemblyInitialize and put it into its own class ApplicationInitializer.

[TestClass]
public class ApplicationInitializer
{
    [AssemblyInitialize]
    public static void AssemblyInitialize(TestContext context)
    {
        var waitForApplicationRun = new TaskCompletionSource<bool>();
        Task.Run(() =>
        {
            var application = new Application();
            application.Startup += (s, e) => { waitForApplicationRun.SetResult(true); };
            application.Run();
        });
        waitForApplicationRun.Task.Wait();        
    }
    [AssemblyCleanup]
    public static void AssemblyCleanup()
    {
        Application.Current.Dispatcher.Invoke(Application.Current.Shutdown);
    }
}
[TestClass]
public class MyTestClass
{
    [TestMethod]
    public void MyTestMethod()
    {
        // implementation can access Application.Current.Dispatcher
    }
}
Patience answered 3/4, 2014 at 9:59 Comment(1)
I like this alot!Poussette
T
2

When you call Dispatcher.BeginInvoke, you are instructing the dispatcher to run the delegates on its thread when the thread is idle.

When running unit tests, the main thread will never be idle. It will run all of the tests then terminate.

To make this aspect unit testable you will have to change the underlying design so that it isn't using the main thread's dispatcher. Another alternative is to utilise the System.ComponentModel.BackgroundWorker to modify the users on a different thread. (This is just an example, it might be innappropriate depending upon the context).


Edit (5 months later) I wrote this answer while unaware of the DispatcherFrame. I'm quite happy to have been wrong on this one - DispatcherFrame has turned out to be extremely useful.

Typecast answered 20/8, 2009 at 3:17 Comment(0)
C
2

Creating a DipatcherFrame worked great for me:

[TestMethod]
public void Search_for_item_returns_one_result()
{
    var searchService = CreateSearchServiceWithExpectedResults("test", 1);
    var eventAggregator = new SimpleEventAggregator();
    var searchViewModel = new SearchViewModel(searchService, 10, eventAggregator) { SearchText = searchText };

    var signal = new AutoResetEvent(false);
    var frame = new DispatcherFrame();

    // set the event to signal the frame
    eventAggregator.Subscribe(new ProgressCompleteEvent(), () =>
       {
           signal.Set();
           frame.Continue = false;
       });

    searchViewModel.Search(); // dispatcher call happening here

    Dispatcher.PushFrame(frame);
    signal.WaitOne();

    Assert.AreEqual(1, searchViewModel.TotalFound);
}
Carcinogen answered 14/10, 2009 at 22:8 Comment(0)
I
2

If you want to apply the logic in jbe's answer to any dispatcher (not just Dispatcher.CurrentDispatcher, you can use the following extention method.

public static class DispatcherExtentions
{
    public static void PumpUntilDry(this Dispatcher dispatcher)
    {
        DispatcherFrame frame = new DispatcherFrame();
        dispatcher.BeginInvoke(
            new Action(() => frame.Continue = false),
            DispatcherPriority.Background);
        Dispatcher.PushFrame(frame);
    }
}

Usage:

Dispatcher d = getADispatcher();
d.PumpUntilDry();

To use with the current dispatcher:

Dispatcher.CurrentDispatcher.PumpUntilDry();

I prefer this variation because it can be used in more situations, is implemented using less code, and has a more intuitive syntax.

For additional background on DispatcherFrame, check out this excellent blog writeup.

Iey answered 15/4, 2013 at 19:20 Comment(1)
Dispatcher.PushFrame(frame); uses Dispatcher.CurrentDispatcher internally... So this wouldn't work.Solidify
C
1

If your goal is to avoid errors when accessing DependencyObjects, I suggest that, rather than playing with threads and Dispatcher explicitly, you simply make sure that your tests run in a (single) STAThread thread.

This may or may not suit your needs, for me at least it has always been enough for testing anything DependencyObject/WPF-related.

If you wish to try this, I can point you to several ways to do this :

  • If you use NUnit >= 2.5.0, there is a [RequiresSTA] attribute that can target test methods or classes. Beware though if you use an integrated test runner, as for example the R#4.5 NUnit runner seems to be based on an older version of NUnit and cannot use this attribute.
  • With older NUnit versions, you can set NUnit to use a [STAThread] thread with a config file, see for example this blog post by Chris Headgate.
  • Finally, the same blog post has a fallback method (which I've successfully used in the past) for creating your own [STAThread] thread to run your test on.
Costplus answered 20/8, 2009 at 9:31 Comment(1)
For very low level unit testing this works, but sometimes you need to test your functions with background threads.Rottweiler
H
1

I'm using MSTest and Windows Forms technology with MVVM paradigm. After trying many solutions finally this (found on Vincent Grondin blog) works for me:

    internal Thread CreateDispatcher()
    {
        var dispatcherReadyEvent = new ManualResetEvent(false);

        var dispatcherThread = new Thread(() =>
        {
            // This is here just to force the dispatcher 
            // infrastructure to be setup on this thread
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { }));

            // Run the dispatcher so it starts processing the message 
            // loop dispatcher
            dispatcherReadyEvent.Set();
            Dispatcher.Run();
        });

        dispatcherThread.SetApartmentState(ApartmentState.STA);
        dispatcherThread.IsBackground = true;
        dispatcherThread.Start();

        dispatcherReadyEvent.WaitOne();
        SynchronizationContext
           .SetSynchronizationContext(new DispatcherSynchronizationContext());
        return dispatcherThread;
    }

And use it like:

    [TestMethod]
    public void Foo()
    {
        Dispatcher
           .FromThread(CreateDispatcher())
                   .Invoke(DispatcherPriority.Background, new DispatcherDelegate(() =>
        {
            _barViewModel.Command.Executed += (sender, args) => _done.Set();
            _barViewModel.Command.DoExecute();
        }));

        Assert.IsTrue(_done.WaitOne(WAIT_TIME));
    }
Hoseahoseia answered 2/3, 2014 at 12:29 Comment(0)
B
1

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<IDispatcher>();

    ClassUnderTest classUnderTest = new ClassUnderTest(dispatcher.Object);

    Action<bool> 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);
}
Barnstorm answered 23/8, 2016 at 12:26 Comment(1)
I like this solution because it is easy to understand.Linolinocut
V
1

How about running the test on a dedicated thread with Dispatcher support?

    void RunTestWithDispatcher(Action testAction)
    {
        var thread = new Thread(() =>
        {
            var operation = Dispatcher.CurrentDispatcher.BeginInvoke(testAction);

            operation.Completed += (s, e) =>
            {
                // Dispatcher finishes queued tasks before shuts down at idle priority (important for TransientEventTest)
                Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle);
            };

            Dispatcher.Run();
        });

        thread.IsBackground = true;
        thread.TrySetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
    }
Verbenaceous answered 30/10, 2017 at 2:9 Comment(0)
S
1

Simplest way I found is to just add a property like this to any ViewModel that needs to use the Dispatcher:

public static Dispatcher Dispatcher => Application.Current?.Dispatcher ?? Dispatcher.CurrentDispatcher;

That way it works both in the application and when running unit tests.

I only had to use it in a few places in my entire application so I didn't mind repeating myself a bit.

Seismograph answered 10/7, 2019 at 11:20 Comment(3)
But even if you use Dispatcher.CurrentDispatcher, you have to get the Dispatcher to run, and not continue your test until it is finished.Rottweiler
@DeniseSkidmore When running the test, the CurrentDispatcher simply becomes the thread that the test is running on, otherwise the method your testing would fail with a null reference exception because Application.Current is null. This should have nothing to do with how the test works.Seismograph
For a single threaded test, that is true. If your unit test isn't low enough level, and spawns another thread which then uses Dispatcher.CurrentDispatcher.Invoke, you need to allow that to run in your primary test thread.Rottweiler
R
1

Winforms has a very easy and WPF compatible solution.

From your unit test project, reference System.Windows.Forms.

From your unit test when you want to wait for dispatcher events to finish processing, call

        System.Windows.Forms.Application.DoEvents();

If you have a background thread that keeps adding Invokes to the dispatcher queue, then you'll need to have some sort of test and keep calling DoEvents until the background some other testable condition is met

        while (vm.IsBusy)
        {
            System.Windows.Forms.Application.DoEvents();
        }
Rottweiler answered 16/9, 2019 at 21:40 Comment(0)
P
0

I suggest adding one more method to the DispatcherUtil call it DoEventsSync() and just call the Dispatcher to Invoke instead of BeginInvoke. This is needed if you really have to wait until the Dispatcher processed all frames. I am posting this as another Answer not just a comment, since the whole class is to long:

    public static class DispatcherUtil
    {
        [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
        public static void DoEvents()
        {
            var frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
                new DispatcherOperationCallback(ExitFrame), frame);
            Dispatcher.PushFrame(frame);
        }

        public static void DoEventsSync()
        {
            var frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background,
                new DispatcherOperationCallback(ExitFrame), frame);
            Dispatcher.PushFrame(frame);
        }

        private static object ExitFrame(object frame)
        {
            ((DispatcherFrame)frame).Continue = false;
            return null;
        }
    }
Pseudo answered 23/6, 2014 at 10:53 Comment(0)
C
0

I'm late but this is how I do it:

public static void RunMessageLoop(Func<Task> action)
{
  var originalContext = SynchronizationContext.Current;
  Exception exception = null;
  try
  {
    SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());

    action.Invoke().ContinueWith(t =>
    {
      exception = t.Exception;
    }, TaskContinuationOptions.OnlyOnFaulted).ContinueWith(t => Dispatcher.ExitAllFrames(),
      TaskScheduler.FromCurrentSynchronizationContext());

    Dispatcher.Run();
  }
  finally
  {
    SynchronizationContext.SetSynchronizationContext(originalContext);
  }
  if (exception != null) throw exception;
}
Collectivize answered 28/8, 2018 at 10:57 Comment(0)
C
0

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);
Cons answered 9/4, 2020 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.