The previous article explains how to perform unit tests on prism and MEF. Today, let's talk about how to test event publishing and subscription eventaggregator in prism? We all know that eventaggregator is available in Prism:
UsingMicrosoft. Practices. Prism. events;
PrivateIeventaggregator theeventaggregator {Get;Set;}
[Importingconstructor]
PublicMyviewmodel (ieventaggregator eventaggregator)
{
Theeventaggregator=Eventaggregator;
//Todo:
}
You can then publish and subscribe the event ):
Theeventaggregator. getevent<Marketpricesupdatedevent>(). Publish (clonedpricelist );
AboveCodeA Custom Event: marketpriceupdatedevent: (defined as the data type you need. Here is idictionary <string, decimal>)
Public ClassMarketpricesupdatedevent: compositepresentationevent<Idictionary<String,Decimal>
{
}
If the last line of a function is to publish an event without returning a value, how can we perform unit testing on it? How can I test whether this event has been publish?
We can write a 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 ()
{
// Note that this is not mock, it is the original one!
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 );
}
}
}
Then the mock event can be used in the unit test class:
[Testmethod]
Public Void Testpublishedevent ()
{
VaR eventagregator = New Mockpriceupdatedeventaggregator ();
VaR marketfeed = New Testablemarketfeedservice (eventagregator );
Assert. istrue (marketfeed. symbolexists ( " Stock0 " ));
Marketfeed. invokeupdateprices ();
// Verify event Publishing
Assert. istrue (eventagregator. mockmarketpriceupdatedevent. publishcalled );
// Validate event parameters
VaR Payload = Eventagregator. mockmarketpriceupdatedevent. publishargumentpayload;
Assert. isnotnull (payload );
Assert. istrue (payload. containskey ( " Stock0 " ));
Assert. areequal (marketfeed. getprice ( " Stock0 " ), Payload [ " Stock0 " ]);
}