skip to the main content area of this page
Patterns and Practices

Moq - Mocking Library Using .NET 3.5 LINQ Expressions Trees and C# 3.0 Lambda Expressions


If you are still writing hand mocks or have not settled on a tool yet for your mocking needs, you may want to check out Moq.

Per the website:

"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, simple, type-safe and refactoring-friendly mocking library available. And it supports mocking interfaces as well as classes."

Moq looks pretty cool. Here are some examples pulled from its QuickStart Page that show off the use of Lambda Expressions:

 

// ShouldExpectCallReturn
var mock = new Mock<ICloneable>();
var clone = new object();
mock.Expect(x => x.Clone()).Returns(clone);
Assert.AreSame(clone, mock.Object.Clone());


// ShouldExpectCallWithArgument
var mock = new Mock<IFoo>();
mock.Expect(x => x.DoInt(1)).Returns(11);
mock.Expect(x => x.DoInt(2)).Returns(22);
Assert.AreEqual(11, mock.Object.DoInt(1));
Assert.AreEqual(22, mock.Object.DoInt(2));


// ShouldExpectCallWithReferenceLazyEvaluate
int a = 25;
var mock = new Mock<IFoo>();
mock.Expect(x => x.DoArgument(a.ToString())).Returns(() => a);
a = 10;
Assert.AreEqual(10, mock.Object.DoArgument("10"));


// ShouldExpectReturnPropertyValue
var mock = new Mock<IFoo>();
mock.Expect(x => x.ValueProperty).Returns(25);
Assert.AreEqual(25, mock.Object.ValueProperty);

 

You can learn more here.


Tags: Moq


Topics



Popular Tags



Recent Links