VirtualStaticVoid
VirtualStaticVoid

Reputation: 1706

Rhino Mocks: How to verify that a constructor was called

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.

Upvotes: 2

Views: 2155

Answers (3)

George Mauer
George Mauer

Reputation: 122052

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.

Upvotes: 4

Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65391

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".

Upvotes: 0

Lee
Lee

Reputation: 144136

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);

Upvotes: 2

Related Questions