Passing Moq mock-objects to constructor

2019-03-17 02:15发布

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; 
    }
    ..
}

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); 

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); 

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?

2条回答
看我几分像从前
2楼-- · 2019-03-17 03:10
var mock = new Mock<IBar>().Object
查看更多
Luminary・发光体
3楼-- · 2019-03-17 03:22

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();

moq docs

查看更多
登录 后发表回答