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

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

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

to test MyService , we need to make fun of Lazy<Dependency> .

I am trying to do 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:

Initializing the Tests.MyServiceTests.MyTestInitialize method exception. System.InvalidCastException: System.InvalidCastException: cannot list an object of type 'System.Lazy 1[IDependency]' to type 'Moq.IMocked 1 [System.Lazy`1 [IDependency]]' ..

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

+5
source share
1 answer

You do not need to make fun of Lazy as part of the framework (with the exception of some extreme circumstances). You can simply make fun of IDependency and pass the tricked 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 means that Lazy essentially not do anything for your tests (if this is a problem) - it will simply return the already created layout when it was first used

+6
source

Source: https://habr.com/ru/post/1244616/


All Articles