views:

305

answers:

3

Is it possible in Rhino.Mocks to verify whether a specified constructor was called?

Consider the following code:

public interface IFoo
{
  void Bar();
}

public class FooFactory
{

  public IFoo CreateInstance(int x, int y)
  {
    return new Foo(x, y);
  }

}

public class Foo : IFoo
{

  public Foo(int x, int y)
  {
    // ... blah
  }

  public void Bar()
  {
    // blah...
  }

}

[TestFixture]
public class FooFactoryTest
{

  [Test]
  public void Assert_Foo_Ctor_Called_By_Factory_CreateInstance()
  {

    MockRepository mocks = new MockRepository();

    using (mocks.Record())
    {
      Expect.Call( /* ???? */ );
    }

    using(mocks.Playback())
    {
      new FooFactory().CreateInstance(1, 2);
    }

    mocks.VerifyAll();

  }

}

I would like to verify that Foo(int, int) was called by the FooFactory.

+2  A: 

I don't think you can do what you're asking. However, if

Foo(int, int)
is the only constructor on Foo then you can simply assert the type of the returned IFoo object i.e.

Assert.IsInstanceOfType(typeof(Foo), foo);

If there is more than one constructor then you'd have to check some external state of the returned object:

Foo f = (Foo)fooReturnedFromFactory;
Assert.AreEqual(1, f.X);
Assert.AreEqual(2, f.Y);
Lee
A: 

Don't think that you can test if the constructor ran directly.

But you could test it indirectly. For example if you set property "A" to 5, you could test the value of property "A".

Shiraz Bhaiji
+4  A: 

Short answer: No, that's not how Rhino Mocks (or any mocking framework I think) works.

Longer answer: You're not really doing this correctly. One of several reasons to use a factory is so that you can mock out when new objects are created - this means that you would be mocking your FooFactory and providing the mock for tests of other objects. Perhaps you have a lot of logic in your factory that you would like to get under test also - consider separating that logic into another class like a builder which can be tested in isolation.

George Mauer
Agreed. I'd strongly question the need to test that a specific constructor was called... sounds like over specification to me. What you should be testing is that the factory produces the expected output based on specific input.
ShaneC