Question

I have an MvvmCross ViewModel that inherits from MvxBase and use's its ViewDispatcher property like this:

    /// Handles a timer elapsed event
    private void TimerOnElapsed(object sender, EventArgs eventArgs)
    {
      ViewDispatcher.RequestMainThreadAction(UpdateEllapsedTime);
    }

The problem is that ViewDispatcher is null when I try to use this ViewModel in a unit test. I am creating and registering a mock dispatcher in the test, but the ViewModel's ViewDispatcher property is by a parent class in the framework to be MvxMainThreadDispatcher.Instance rather then being resolved from the IoC container.

The workaround I am currently using is the following:

    private void TimerOnElapsed(object sender, EventArgs eventArgs)
    {
        if (ViewDispatcher != null)
        {
            ViewDispatcher.RequestMainThreadAction(UpdateEllapsedTime);
        }
        else
        {
            UpdateEllapsedTime();
        }
    }

I don't want to add code into a class for the sole purpose of getting unit tests to work, but I don't think its a big deal in this case. However, I'm still wondering if there is a better way to make this ViewModel testable.

Was it helpful?

Solution

The ViewDispatcher is cached in the MvxMainThreadDispatcher.Instance reference as an optimization (and also because of some legacy reasons).

However, it's still also registered in the IOC system too.

To use it in unit tests, the simplest route is to use a mock dispatcher like that in the n29 MvvmCross video - https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/blob/master/N-29-TipCalcTest/TipCalcTest.Tests/MockDispatcher.cs

This singleton is created and registered using code like:

var mockDispatcher = new MockDispatcher();
        Ioc.RegisterSingleton<IMvxViewDispatcher>(mockDispatcher);
        Ioc.RegisterSingleton<IMvxMainThreadDispatcher>(mockDispatcher);

and can be cleared within tests using ClearAll() on MvxIoCSupportingTest


if you think this should be cleaned up in future Mvx versions, there is an open issue on https://github.com/MvvmCross/MvvmCross/issues/542 - people can comment and contribute there

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top