[Silverlight入门系列]Prism的事件EventAggregator如何单元测试UnitTesting
时间:2011-06-07 来源:Mainz
上一篇说了如何进行Prism和MEF的单元测试,今天来说一下Prism中的事件发布和订阅EventAggregator如何进行测试?大家知道在Prism中可用EventAggregator:
using Microsoft.Practices.Prism.Events;
private IEventAggregator TheEventAggregator { get; set; }
[ImportingConstructor]
public MyViewModel(IEventAggregator eventAggregator)
{
TheEventAggregator = eventAggregator;
//TODO:
}
然后可以进行事件的发布(Publish)和订阅(Subscribe):
TheEventAggregator.GetEvent<MarketPricesUpdatedEvent>().Publish(clonedPriceList);
上面代码中用到了一个自定义的Event: MarketPriceUpdatedEvent: (定义成你需要的数据类型就可以了,这里是IDictionary<string, decimal>)
public class MarketPricesUpdatedEvent : CompositePresentationEvent<IDictionary<string, decimal>>
{
}
如果一个函数最后一行是发布一个事件,没有返回值,如何对它进行单元测试?如何测试这个事件已经Publish了呢?
我们可以自己写一个Mock的EventAggregator:
class MockEventAggregator : IEventAggregator
{
Dictionary<Type, object> events = new Dictionary<Type, object>();
public TEventType GetEvent<TEventType>() where TEventType : EventBase, new()
{
return (TEventType)events[typeof(TEventType)];
}
public void AddMapping<TEventType>(TEventType mockEvent)
{
events.Add(typeof(TEventType), mockEvent);
}
}
class MockPriceUpdatedEventAggregator : MockEventAggregator
{
public MockMarketPricesUpdatedEvent MockMarketPriceUpdatedEvent = new MockMarketPricesUpdatedEvent();
public MockPriceUpdatedEventAggregator()
{
//注意这个不是Mock的,是原来的!
AddMapping<MarketPricesUpdatedEvent>(MockMarketPriceUpdatedEvent);
}
public class MockMarketPricesUpdatedEvent : MarketPricesUpdatedEvent
{
public bool PublishCalled;
public IDictionary<string, decimal> PublishArgumentPayload;
public EventHandler PublishCalledEvent;
private void OnPublishCalledEvent(object sender, EventArgs args)
{
if (PublishCalledEvent != null)
PublishCalledEvent(sender, args);
}
public override void Publish(IDictionary<string, decimal> payload)
{
PublishCalled = true;
PublishArgumentPayload = payload;
OnPublishCalledEvent(this, EventArgs.Empty);
}
}
}
然后在单元测试类里面就可以用这个mock的事件了:
[TestMethod]
public void TestPublishedEvent()
{
var eventAgregator = new MockPriceUpdatedEventAggregator();
var marketFeed = new TestableMarketFeedService(eventAgregator);
Assert.IsTrue(marketFeed.SymbolExists("STOCK0"));
marketFeed.InvokeUpdatePrices();
//验证事件发布
Assert.IsTrue(eventAgregator.MockMarketPriceUpdatedEvent.PublishCalled);
//验证事件的参数
var payload = eventAgregator.MockMarketPriceUpdatedEvent.PublishArgumentPayload;
Assert.IsNotNull(payload);
Assert.IsTrue(payload.ContainsKey("STOCK0"));
Assert.AreEqual(marketFeed.GetPrice("STOCK0"), payload["STOCK0"]);
}
相关阅读 更多 +