Rhino Mocks: how to check that a constructor was called

Is it possible in Rhino.Mocks to check if a specified constructor has been specified?

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 check that Foo (int, int) was called by FooFactory.

+2


source to share


3 answers


Short Answer : No, this is not how Rhino Mocks (or any mocking framework I think) works.



Longer answer . You are actually doing it wrong. One of the several reasons for using a factory is that you can mock the creation of new objects - this means you will mock your FooFactory and provide a mock for testing other objects. Perhaps you have a lot of logic in your factory logic that you would like to test as well - consider splitting that logic into another class, such as a builder, that you can test in isolation.

+4


source


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

Foo (int, int)
is the only constructor on Foo, then you can simply assert the return type of the IFoo ie
Assert.IsInstanceOfType (typeof (Foo), foo);


If there is more than one constructor, you need to check the external state of the returned object:

Foo f = (Foo) fooReturnedFromFactory;
Assert.AreEqual (1, fX);
Assert.AreEqual (2, fY);
+2


source


Don't feel like you can check if the constructor works directly.

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

0


source







All Articles