2009-03-12 4 views
3

J'utilise l'agrégateur d'événements Composite Application Library, et je voudrais créer un simulacre pour l'interface IEventAggregator, pour l'utiliser dans mon test unitaire.Mocking the CAL EventAggregator avec Moq

Je prévois sur l'utilisation Moq pour cette tâche, et un test d'exemple afin ressemble beaucoup quelque chose comme ceci:

var mockEventAggregator = new Mock<IEventAggregator>(); 
var mockImportantEvent = new Mock<ImportantEvent>(); 
mockEventAggregator.Setup(e => e.GetEvent<SomeOtherEvent>()).Returns(new Mock<SomeOtherEvent>().Object); 
mockEventAggregator.Setup(e => e.GetEvent<SomeThirdEvent>()).Returns(new Mock<SomeThirdEvent>().Object); 
// ... 
mockEventAggregator.Setup(e => e.GetEvent<ImportantEvent>()).Returns(mockImportantEvent.Object); 

mockImportantEvent.Setup(e => e.Publish(It.IsAny<ImportantEventArgs>())); 

// ...Actual test... 

mockImportantEvent.VerifyAll(); 

Cela fonctionne très bien, mais je voudrais savoir, s'il y a une façon intelligente de éviter d'avoir à définir une maquette vide pour chaque type d'événement que mon code pourrait rencontrer (SomeOtherEvent, SomeThirdEvent, ...)? Je pourrais bien sûr définir tous mes événements de cette façon dans une méthode [TestInitialize], mais j'aimerais savoir s'il y a une manière plus intelligente? :-)

Répondre

1

J'ai trouvé la solution pour celui-ci:

var mockEventAggregator = new Mock<IEventAggregator>{ DefaultValue = DefaultValue.Mock }; 

fera le retour de mockEventAggregator se moque de tous les objets imbriqués.