tags:

views:

391

answers:

3

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
    }

}
+2  A: 
var myIFoo = MockRepository.GenerateStub<IFoo>();

you can check awesomeness happened via

myIFoo.AssertWasCalled(f => f.DoSomethingAwesome());
Andrew Bullock
+3  A: 

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.

Jon Skeet
Well it preety obvious now that you said it. :)
Miyagi Coder
+1  A: 

It's been awhile since I used Rhino but I believe you can do:

mockRespository.StrictMock<Foo>( ibarVariable )

However it won't really work unless all of Foo's members are virtual.

Tinister