Moq事件聚合器是否可能

时间:2010-09-12 08:19:38

标签: moq prism

想知道它是否可能让Moq成为Prism EventAggregator 我们来看看他们有的EventAggregator快速入门

     [TestMethod]
      public void PresenterPublishesFundAddedOnViewAddClick()
      {
         var view = new MockAddFundView();
         var EventAggregator = new MockEventAggregator();
         var mockFundAddedEvent = new MockFundAddedEvent();
         EventAggregator.AddMapping<FundAddedEvent>(mockFundAddedEvent);
         var presenter = new AddFundPresenter(EventAggregator);
         presenter.View = view;
         view.Customer = "99";
         view.Fund = "TestFund";
         view.PublishAddClick();
         Assert.IsTrue(mockFundAddedEvent.PublishCalled);
         Assert.AreEqual("99", mockFundAddedEvent.PublishArgumentPayload.CustomerId);
      }       

    I have tried to convert the above using moq but I get problems 

他们有MockEventAggregator。我怎么能用Moq做到这一点?

public class MockEventAggregator : IEventAggregator
{
    Dictionary<Type, object> events = new Dictionary<Type, object>();
    public TEventType GetEvent<TEventType>() where TEventType : EventBase
    {
        return (TEventType)events[typeof(TEventType)];
    }

    public void AddMapping<TEventType>(TEventType mockEvent)
    {
        events.Add(typeof(TEventType), mockEvent);
    }
}

有没有人使用过MOQ,EventAggregator有没有任何例子? 非常感谢

修改

关注GrameF后,我添加了仍然无效的代码。可以帮助

            [TestMethod]
            public void PresenterPublishesFundAddedOnViewAddClick2()
            {

                //Arrange
                var view = new Mock<IAddFundView>();
                var fakeEventAggregator = new Mock<IEventAggregator>();
                var fakeMyEvent = new Mock<FundAddedEvent>();
                fakeEventAggregator.Setup(x => x.GetEvent<FundAddedEvent>()).Returns(fakeMyEvent.Object); 

                var presenter = new AddFundPresenter(fakeEventAggregator.Object) {View = view.Object};
                fakeMyEvent.Verify(x => x.Publish(It.IsAny<FundOrder>())); **//CRASHES** HERE



                //view.PublishAddClick();
                //view.Customer = "99";
                //view.Fund = "TestFund";

                //view.PublishAddClick();

                ////Assert 
                //Assert.IsTrue(mockFundAddedEvent.PublishCalled);
                //Assert.AreEqual("99", mockFundAddedEvent.PublishArgumentPayload.CustomerId);
                //Assert.AreEqual("TestFund", mockFundAddedEvent.PublishArgumentPayload.TickerSymbol);
            }

1 个答案:

答案 0 :(得分:14)

是的,有可能,您只需将其设置为返回模拟事件,您可以在其上验证是否已调用PublishSubscribe

var fakeEventAggregator = new Mock<IEventAggregator>();
var fakeMyEvent = new Mock<MyEvent>();

fakeEventAggregator.
    Setup(x => x.GetEvent<MyEvent>()).
    Returns(fakeMyEvent.Object);

var test = new Foo(fakeEventAggregator.Object);
test.PublishAnEvent();

fakeMyEvent.Verify(x => x.Publish(It.IsAny<MyEventArgs>()));