文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>[Silverlight入门系列]Prism的事件EventAggregator如何单元测试UnitTesting

[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"]);
}
相关阅读 更多 +
排行榜 更多 +
城市英雄机甲救援手游

城市英雄机甲救援手游

动作格斗 下载
星战模拟器MOD内置菜单

星战模拟器MOD内置菜单

模拟经营 下载
解压盒下载包

解压盒下载包

休闲益智 下载