6

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.

dampee
  • 3,392
  • 1
  • 21
  • 37
  • Why not mock `IDependency`, and then pass in `new Lazy(mockedObj)` (or however it's built - I forgot)? There's no reason to mock `Lazy`, you're not testing the system framework. – Rob Mar 07 '16 at 22:30
  • Good idea, but I can't get it to work. You need to pass a lambda. MockedObj isn't accepted. – dampee Mar 07 '16 at 22:32
  • Then pass something like `new Lazy(() => mockedObj)` :) – Rob Mar 07 '16 at 22:33
  • 1
    Doh. Forgot the type. It's Lazy(() => automockedObject). Thanks a lot. If you put this in the response, i'll mark it as an answer. – dampee Mar 07 '16 at 22:35

1 Answers1

6

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

Rob
  • 26,989
  • 16
  • 82
  • 98
  • 1
    For those interested I got a similar response from the automock guys: https://github.com/autofac/Autofac.Extras.Moq/issues/3 – dampee Mar 07 '16 at 22:57