MVVM Light DispatcherHelper & Unit Testing with MSTest

I considered the question of this as an additional question in this thread:

Unit testing with MVVM Light and DispatcherHelper

but since I delved into it, I think it is a little different.

I have one project containing models / views, a separate project containing models, and a third separate unit test (MSTest) project containing tests for models. I use MVVM Light DispatcherHelper to help me work in the background task, but to get errors from this task back to the user interface.

The view / view project has an App.xaml.cs file that contains an OnStartup event handler in which I put the DispatcherHelper.Initialize () call. One of the virtual machines calls one of the long-term methods of the model in another thread using .BeginInvoke () delegation:

     FileProcessDelegate processor = GenerateAddressingFile;
     processor.BeginInvoke(FileGenerationComplete, null);

In this long-running method, it calls a utility method to send errors back to the user interface. They are presented as mvvm-light messages that are sent using DispatcherHelper.CheckBeginInvokeOnUI ()

    internal static void ReportErrorToUi(IFileError error)
    {
        DispatcherHelper.CheckBeginInvokeOnUI(
            () => Messenger.Default.Send(new GenericMessage<IFileError>(error), MessageTokens.ReportFileError));
    }

All this works great in the app.

In one of the unit test classes for the model, I try to verify that the long-term method correctly sends messages when errors occur. In this test class, I have a call to DispatcherHelper.Initialize () in the initialization method of the MSTest class.

    #region Additional test attributes
    // 
    //You can use the following additional attributes as you write your tests:
    //
    //Use ClassInitialize to run code before running the first test in the class
    [ClassInitialize]
    public static void MyClassInitialize(TestContext testContext)
    {
        DispatcherHelper.Initialize();
    }

, , , . , DispatcherHelper.CheckBeginInvokeOnUI() , , .

, , . , .

, . , , DispatcherHelper.CheckBeginInvokeOnUI(), DispatcherHelper.UIDispatcher.Thread , .

?

+3
2

, - , Mvvm Light, , , :

DispatcherHelper, , Mvvm Light, Initialize():

    public static void Initialize()
    {
        if (UIDispatcher != null &&
            UIDispatcher.Thread.IsAlive)
        {
            return;
        }
        UIDispatcher = Dispatcher.CurrentDispatcher;
    }

- :

&& UIDispatcher.Thread.IsAlive

. DispatcherHelper.Initialize() MyTestInitialize() unit test. , , UIDispatcher, , DispatcherHelper Dispatcher/Thread, .

-, VSTS "" , . MyClassInitialize() , . Mvvm Light DispatcherHelper , DispatcherHelper.Initialize() , UIDispatcher , .

+3

. , , , , . ( ) ?

Jonas Follesoe Silverlight, http://jonas.follesoe.no/2007/09/18/unit-testing-event-based-asynchronous-code/. unit test .

, , Laurent

0

Source: https://habr.com/ru/post/1786223/


All Articles