传递起订量模拟对象构造器 [英] Passing Moq mock-objects to constructor

查看:189
本文介绍了传递起订量模拟对象构造器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用RhinoMocks了好一段时间,但刚刚开始考虑起订量。我有一个很基本的问题,我很惊讶,这并不正确飞开箱。假设我有以下类定义:

I've been using RhinoMocks for a good while, but just started looking into Moq. I have this very basic problem, and it surprises me that this doesn't fly right out of the box. Assume I have the following class definition:

public class Foo
{
    private IBar _bar; 
    public Foo(IBar bar)
    {
        _bar = bar; 
    }
    ..
}

现在我有一个测试,我需要模拟发送到富的伊巴尔。在RhinoMocks我只是不喜欢它遵循,和它的工作好了:

Now I have a test where I need to Mock the IBar that send to Foo. In RhinoMocks I would simply do it like follows, and it would work just great:

var mock = MockRepository.GenerateMock<IBar>(); 
var foo = new Foo(mock); 

然而,在Moq的这似乎并没有以相同的方式工作。我做如下:

However, in Moq this doesn't seem to work in the same way. I'm doing as follows:

var mock = new Mock<IBar>(); 
var foo = new Foo(mock); 

不过,现在它失败? - ?告诉我无法从'Moq.Mock'转换为'伊巴尔什么我做错了什么是最小起订量这样的推荐方法

However, now it fails - telling me "Cannot convert from 'Moq.Mock' to 'IBar'. What am I doing wrong? What is the recommended way of doing this with Moq?

推荐答案

您需要穿过模拟的对象实例

You need to pass through the object instance of the mock

var mock = new Mock<IBar>();  
var foo = new Foo(mock.Object);

您也可以使用模拟对象访问实例的方法。

You can also use the the mock object to access the methods of the instance.

mock.Object.GetFoo();

起订量文档

这篇关于传递起订量模拟对象构造器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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