How to mock the IMessageBroker
On the blogs there are a lot of articles about the M-V-VM pattern showing how to decouple the various components of our application to make it modular.
One of the component that helps the ViewModels to communicate with other ViewModels is the MessageBroker (AKA EventAggregator, AKA Mediator): a manager class that route the messages from the ViewModels.
One good implementation of the Mediator for the MVVM is this http://sachabarber.net/?p=477:
To make it more testable we extract an interface:
public interface IMessageBroker { void NotifyColleagues(MessageType messageType); void Register<T>(Action<T> action, MessageType messageType); }
If you TDD your application or if you write unit test you could need to mock the IMessageBroker and it’s not immediate because the Action<T>.
Alessandro wrote a solution that is interesting using Moq:
[Fact] public void Sample_Test() { Mock<IMessageBroker> broker = new Mock<IMessageBroker>(); Action<String> action = null; broker .Setup(b => b.Subscribe(It.IsAny<Action<String>>())) .Callback<Action<String>>(a => action = a); new FakeViewModel(broker.Object); action.Invoke("TestMessage"); // Asserts... }
Moq is a powerful mock framework and it’s simplicity make the elegant and easy to read!
No comments
RSS


