Passing Moq mock-objects to constructor

C#.NetMockingMoq

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

The previous answers are correct but just for the sake of completeness I would like add one more way. Using Linq feature of the moq library.

public interface IBar
{
    int Bar(string s);
    
    int AnotherBar(int a);
}

public interface IFoo
{
    int Foo(string s);
}

public class FooClass : IFoo
{
    private readonly IBar _bar;

    public FooClass(IBar bar)
    {
        _bar = bar;
    }

    public int Foo(string s) 
        => _bar.Bar(s);

    public int AnotherFoo(int a) 
        => _bar.AnotherBar(a);
}

You could use Mock.Of<T> and avoid .Object call.

FooClass sut = new FooClass(Mock.Of<IBar>(m => m.Bar("Bar") == 2 && m.AnotherBar(1) == 3));
int r = sut.Foo("Bar"); //r should be 2
int r = sut.AnotherFoo(1); //r should be 3

or using matchers

FooClass sut = new FooClass(Mock.Of<IBar>(m => m.Bar(It.IsAny<string>()) == 2));
int r = sut.Foo("Bar"); // r should be 2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionstiank81View Question on Stackoverflow
Solution 1 - C#skyfootView Answer on Stackoverflow
Solution 2 - C#Massimiliano PelusoView Answer on Stackoverflow
Solution 3 - C#JohnnyView Answer on Stackoverflow