简体   繁体   中英

How to write unit tests that use MVVM Light's Messenger?

I'm working on writing some unit tests for a WPF app that uses MVVM Light's Messenger. We've got several methods that look like similar to this:

private void ExecuteViewTemplatesCommand()
{
    OpenViewMessage message = new OpenViewMessage();
    CurrentViewModel = message.ViewModel = ViewModelLocator.TemplateVM;
    Messenger.Default.Send<OpenViewMessage>(message);
}

I figure I've got to write unit tests which work against the side effects that running a method that is of type void will do, like in this case assign the message to a property of the Messenger object. How do I unit tests for this situation, please?

In order to write unit test for mvvm light you will need to first register the message, and know when to send the message Let's say you have 2 classes in your viewmodel that is not tightly couple, we'll call them classA and classB. Here is the process that can be use to register and send the message.

ClassA //register the message
{
          MessengerInstance.Register<//in here you can put the class that you want to register, for the sake to simplify the example, we'll introduce this as classC>(this, DelegateFunctionHanlder);
}

private void DelegateFunctionHanlder(classC message)
{
    //in here, we'll do something
}

Then you'll need to create the classC as a messageclass, this will act as mediator class, which is a messenger

namespace something
{
    public class ClassC
    {
        //it can be blank
    }
}

Then create a ClassB

ClassB
{
    classC _classCMessage = new classC();
    MessengerInstace.Send(_classCMessage);

}

The point here is that all of this prevent ClassA directly talk to ClassB, the reason being is that we try to avoid any type of dependency, assume classB is a WPF framework, we will try to avoid to depend on that in case one day you decide to switch to different framework

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM