Offset objects using Moq when the constructor has parameters

I have an object that I am trying to make fun of with moq. The constructor of the object has the necessary parameters:

public class CustomerSyncEngine { public CustomerSyncEngine(ILoggingProvider loggingProvider, ICrmProvider crmProvider, ICacheProvider cacheProvider) { ... } } 

Now I'm trying to create a layout for this object using the syntax moq v3 "setup" or v4 "Mock.Of", but I can’t figure it out ... everything I try does not check. Here is what I still have, but the last line gives me the real object, not the layout. The reason I do this is because I have methods on CustomerSyncEngine that I want to test, is called ...

 // setup var mockCrm = Mock.Of<ICrmProvider>(x => x.GetPickLists() == crmPickLists); var mockCache = Mock.Of<ICacheProvider>(x => x.GetPickLists() == cachePickLists); var mockLogger = Mock.Of<ILoggingProvider>(); // need to mock the following, not create a real class like this... var syncEngine = new CustomerSyncEngine(mockLogger, mockCrm, mockCache); 
+52
moq
Sep 14 '11 at 10:22
source share
2 answers

The last line gives you a real instance because you are using a new keyword, not a mocking CustomerSyncEngine.

You should use Mock.Of<CustomerSyncEngine>()

The only problem with Mocking Concrete types is that Moq will need a public default constructor (no parameters) OR you need to create a Moq specification with arg constructor. http://www.mockobjects.com/2007/04/test-smell-mocking-concrete-classes.html

The best thing you need to do is right-click on your class and select the Extract interface.

+21
Sep 18 2018-11-11T00: 00Z
source share

Change the last line to

 var syncEngine = new Mock<CustomerSyncEngine>(mockLogger.Object,mockCrm.Object,mockCache.Object); 

and he should work

+34
Jul 09 2018-12-12T00:
source share



All Articles