Mocking objects in C# with Moq

Moq can come in handy for unit tests. Let us assume you have a View and a Presenter. The View as part of the GUI manages user input and therefore hands over events to the Presenter. The presenter then computes something based on these events. When unit testing triggering these events can be very difficult.
So why not just mock the View with Moq?

Here are two nifty ideas for your unit tests:

[TestMethod]
public void UnitTest1()
{
    IPresenter presenter = new Presenter();
    int initial = presenter.MyProperty;
    var viewMock = new Mock();

    //we now raise ViewEvent from the view
    viewMock.Raise(e => e.ViewEvent += null);

    //the presenter listens on it and does something to MyProperty
    int final = presenter.MyProperty;
    Assert.IsTrue(initial != final);
}
[TestMethod]
public void UnitTest2()
{
    IPresenter presenter = new Presenter();
    var viewMock = new Mock();

    //we now run a method on presenter that should update the view
    presenter.RunUpdateView();

    //Now we want to check that the update method of the view
        //has been called with an IEnumerable of MyData
    viewMock.Verify(f => f.Update(It.IsAny>(), Times.AtLeastOnce());
}

For more information on Moq check out http://code.google.com/p/moq/wiki/QuickStart

By @Gerald in
Tags : #testing, #c#, #programming,