Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock an object with a constructor - Rhino Mocks

Tags:

c#

rhino-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
    }

}
like image 389
Miyagi Coder Avatar asked Aug 18 '09 14:08

Miyagi Coder


1 Answers

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.

like image 92
Jon Skeet Avatar answered Sep 22 '22 00:09

Jon Skeet