Search code examples
c#moqautofacmstestautomocking

How can you use Lazy<> with AutoMock (Moq)


We are using Autofac.Extras.Moq.AutoMock. Now I have a constructor dependency using Lazy<>

public MyService(Lazy<IDependency> myLazyDependency) {...}

to test MyService we need to mock the Lazy<Dependency>.

I am trying this with

[ClassInitialize]
public static void Init(TestContext context)
{
    autoMock = AutoMock.GetLoose();
}

[TestInitialize]
public void MyTestInitialize()
{
     var myDepMock = autoMock.Mock<Lazy<IDependency>>();  // <-- throws exception
}

This is the exception returned by the test runner:

Initialization method Tests.MyServiceTests.MyTestInitialize threw exception. System.InvalidCastException: System.InvalidCastException: Unable to cast object of type 'System.Lazy1[IDependency]' to type 'Moq.IMocked1[System.Lazy`1[IDependency]]'..

So, how can I pass a Lazy<> mocked object using automock.


Solution

  • You needn't mock Lazy, as it's part of the framework (barring some extreme circumstances). You can simply mock IDependency and pass the mocked object to Lazy.

    Something like this should work:

    var mockDependency = autoMock.Mock<IDependency>();
    var mockObject = mockDependency.Object; //(Not entirely sure of the property for this library)
    var mockedLazy = new Lazy<IDependency>(() => mockObject);
    

    Note that this will mean Lazy essentially will do nothing for your tests (if that's an issue) - it'll simply return the already created mock when it's first used