C# – Mock an object with a constructor – Rhino Mocks

crhino-mocks

How do I mock an object with a constructor using Rhino Mocks?

For example how would this object be mocked…

public class Foo : IFoo
{
    private IBar bar;
    public Foo (IBar bar)
    {
        this.bar = bar
    }

    public DoSomeThingAwesome()
    {
       //awesomeness happens here
    }

}

Best Answer

You don't mock Foo - you mock IFoo. To test Foo itself, you mock IBar and pass the mock into the constructor.

You should try to avoid having things which rely on IFoo explicitly constructing instances of Foo: they should either be given a factory if IFoo somehow, or have an IFoo explicitly passed to them.