Mocking A Lazy Object

I was writing a test for a class that takes a Lazy object as a dependency via the constructor. Like this:

public class DependentThing
{
	public DependentThing(Lazy<ISomeService> _service)
	{
		//construct object
	}
}

I'm using the Moq mocking library to create mocks for my tests. In order to mock the lazy parameter I used the Lazy constructor that takes a lambda expression to instantiate the object. That code looks like this:

var serviceMock = new Mock<ISomeService>();            
DependentThing thing = 
 new DependentThing(new Lazy<ISomeService>(() => serviceMock.Object));

That did the trick but the code looked a little bloated to me. I have a class that takes multiple constructor parameters that are lazy objects and the mocked out constructor began to get long and difficult to read. To fix that I created an extension method that will work with any Mock<T> and will return a Lazy instance of the mock object.

public static class MockExtensions
{
	public static Lazy<T> ToLazy<T>(this Mock<T> mock) where T : class
	{
		return new Lazy<T>(() => mock.Object);

	}
}

Using the new ToLazy() method my mocked out constructor is much shorter and easier to read. The new code looks like this:

var serviceMock = new Mock<ISomeService>();            
DependentThing thing = new DependentThing(serviceMock.ToLazy());
Posted by Matt @ 6:36 PM
22987 Views