Passing Moq mock-objects to constructor

stiank81 picture stiank81 · Aug 10, 2011 · Viewed 24.6k times · Source

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?

Answer

skyfoot picture skyfoot · Aug 10, 2011

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