当构造函数具有参数时,用Moq模拟对象 [英] Mocking objects with Moq when constructor has parameters

查看:93
本文介绍了当构造函数具有参数时,用Moq模拟对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要尝试使用最小起订量模拟的对象.对象的构造函数具有必需的参数:

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

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

现在,我正在尝试使用moq的v3设置"或v4"Mock.Of"语法为此对象创建模拟,但无法弄清楚……我尝试的所有操作均未通过验证.这是我到目前为止的内容,但是最后一行是给我一个真实的对象,而不是模拟对象.我这样做的原因是因为我要验证的CustomerSyncEngine上有一些方法被称为...

Now I'm trying to create the mock for this object using either moq's v3 "setup" or v4 "Mock.Of" syntax but can't figure this out... everything I'm trying isn't validating. Here's what I have so far, but the last line is giving me a real object, not the mock. The reason I'm doing this is because I have methods on the CustomerSyncEngine I want to verify are being 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);

推荐答案

最后一行为您提供了一个真实的实例,因为您使用的是new关键字,而不是嘲笑CustomerSyncEngine.

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

您应该使用Mock.Of<CustomerSyncEngine>()

模拟具体类型的唯一问题是Moq需要一个公共默认构造函数(不带参数),或者您需要使用构造函数arg规范创建Moq. http://www.mockobjects.com/2007/04 /test-smell-mocking-concrete-classes.html

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.

这篇关于当构造函数具有参数时,用Moq模拟对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆