Passing Moq mock-objects to constructor

Solution 1:

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:

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

Solution 3:

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