Testing Events Using Rhino Mocks

There are possible more 'elegant' methods for the below but these are fairly well understandable by someone new to Rhino Mocks or mocking in general.

Testing Event Subscription

Sometimes we want to ensure that a given event has been subscribed to. The following example is essentially testing that when a new ViewModel is instantiated (the constructor accepts an IWorkPackageCoordinator as a dependency), that the events declared on the IWorkPackageCoordinator instance have been subscribed to (by the ViewModel instance). In other words: does the ViewModel subscribe to the IWorkPackageCoordinatorevents.

To test this we create a ViewModel and pass it a mock object that has been created for us by Rhino Mocks.

 

            MockRepository mocks = new MockRepository();
            IWorkPackageCoordinator mockWPC = (IWorkPackageCoordinator)mocks.StrictMock(typeof(IWorkPackageCoordinator));

            // Tell Rhino Mocks that we expect the following events to be subscriped to
            //  - we don't care about the actual delegate that is attached hence the
            // LastCall.IgnoreArguments();
            mockWPC.Downloading += null;
            LastCall.IgnoreArguments();

            mockWPC.Loading += null;   
            LastCall.IgnoreArguments();

            mockWPC.Processing += null;
            LastCall.IgnoreArguments();

            mockWPC.Saving += null;
            LastCall.IgnoreArguments();

            mocks.ReplayAll();

            new ViewModel(mockWPC);
           
            mocks.VerifyAll();  

 

Testing Event Raising\Handling

Another test that is useful is that the object we are testing performs some action when another object raises an event that it is subscribed to.

In the example below we want to test that when an IWorkPackageCoordinator raises it's Downloading event that the ViewModel in turn raises it's PropertyChanged event. We use a boolean eventRaised, and (using lambda syntax) create an anonymous event handler for the PropertyChanged event which sets eventRaised to true if the event is fired. We then tell out Rhino Mock object to raise the Downloading event (in this example with non specific event arguments 'EventArgs.Empty')

            var mockWPC = MockRepository.GenerateMock<IWorkPackageCoordinator>();
            var SUT = new ViewModel(mockWPC);

            bool eventRaised = false;

            SUT.PropertyChanged += (s, e) => { eventRaised = true; };

            // tell mock to raise event
            mockWPC.Raise(x => x.Downloading += null, this, EventArgs.Empty);

            Assert.IsTrue(eventRaised);

 

SHARE: