Aug 25, 2010

Why I love RhinoMocks?

Well, to begin with I really do :)

Anyway, currently I am involved in several projects simultaneously. And it turned out that each project has it's own 3-rd party libraries and tools. Well, one has RhinoMocks and the other has Moq. I do not mind learning new things so I thought why not to try Moq.

Everything went well (without documentation reading) until I decided to create a mock of the —Ālass with "virtual" method. The test was simply to check whether the method gets called. I wrote the test and it failed. Well, I added good code - failed again. Went through the debug - failed anyway :) What could go wrong?

Here is my class I had to mock:
    public class MyViewModel : ViewModelBase    
    {
        public MyViewModel(IEventAggregator events)
        {
            this.eventAggregator = events;
            this.SubscribeToEvents();
        }

        // ... Lot's of other code.

        public virtual void VerifyCurrentView()
        {
            // Smart things here
        }
    }


The class subscribes to certain events from event aggregator and tries to call VerifyCurrentView method after events are handled.

So, how would you check whether the VerifyCurrentView method code actually gets called?
Never mind, here is how I thought I could do this:

    var vm = new Mock< MyViewModel >(events);

Guess what? The constructor never gets called in this case :( I spent an hour trying to figure this out - no luck.

Consequently, the following test (mock) does not work:

[Test]
    public void My_test_Moq_version()
    {
        var events = new EventAggregator();
        var vm = new Mock< MyViewModel >(events);


        vm.Setup(m => m.VerifyCurrentView());


        // Act
        events.GetEvent< AlertHistoryLoadedEvent >()
            .Publish(new HistoryTypeInfo[0]);


        vm.VerifyAll();
    }

And I had no idea why it was happening and neither a desire to know "the truth". I spent another 5 minutes to write the same with RhinoMocks:

[Test]
        public void My_test()
        {
            var events = new EventAggregator();
            var vm = MockRepository.GenerateMock(events);


            // Act
            events.GetEvent()
                  .Publish(new HistoryTypeInfo[0]);


            vm.AssertWasCalled(c => c.VerifyCurrentView());
        }

And it works! Just like that.
RhinoMocks just rocks!

No comments: