Mocking objects with Moq when constructor has parameters

后端 未结 2 1283
[愿得一人]
[愿得一人] 2020-12-09 00:36

I have an object I\'m trying to mock using moq. The object\'s constructor has required parameters:

public class CustomerSyncEngine {
    public CustomerSyncE         


        
相关标签:
2条回答
  • 2020-12-09 00:54

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

    You should use Mock.Of<CustomerSyncEngine>()

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

    The best thing to do would be right click on your class and choose Extract interface.

    0 讨论(0)
  • Change the last line to

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

    and it should work

    0 讨论(0)
提交回复
热议问题