Wednesday, April 13, 2011

I love moq

Moq (pronounced "Mock-you" or just "Mock") is the only mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, type-safe and refactoring-friendly mocking library available.

Mocking frameworks allow you to mock out interfaces and then wield magical powers over them by having methods return whatever values you want, start firing events and even raise exceptions. All so you can focus on testing your code without the pain of setting up the implementation of the Interface to do all the various things it needs to do for you to properly exercise your code.

Set up a Property to return a certain value
_mockModel.Setup(m => m.Description).Returns("Description");

Fire an event from the mock with certain event args
_mockModel.Raise(m => m.DownloadStarted += null, EventArgs.Empty);

Raise an exception with certain arguments
_mockModel.Setup(m => m.ResumePendingDownload()).Throws(new InvalidOperationException("error"));

Verify (like NUnit's Assert) that a method was called on the mock with certain parameters
_mockView.Verify(v => v.ShowDownloadProgressView("Progress"));

Slightly more advanced setups can also be achieved with ridiculous ease.

Verify that a method was called on the mock but you don't know the exact parameters at design-time? You can use the It.IsAny<T> feature when you know the type expected.

_mockView.Verify(v => v.ShowDownloadProgressView(It.IsAny<string>());

Verify how many times a method is called
_mockView.Verify(v => v.ShowDownloadProgressView(It.IsAny<string>()), Times.Exactly(1));

Pretty cool...

No comments:

Post a Comment