How to mock windsor container in order to test registration

For educational purposes, how should I setup a mock of IWindsorContainer, so I can unit test performed registration?

Suppose I have a method like this:

public void MakeRegistration<S, T>(IWindsorContainer container)
   where S : class
   where T : class, S
{
   container.Register(Component.For<S>().ImplementedBy<T>().LifeStyle.Transient);
}

I would like to write a unit test for it, using Moq:

var container = new Mock<IWindsorContainer>(MockBehavior.Strict);
container.Setup(c => c.Register(
      Component.For<IFoo>()
      .ImplementedBy<Foo>()
      .LifeStyle.Transient));

var registrar = new MyRegistrar();
registrar.MakeRegistration<IFoo, Foo>(container.Object);

The above fails, as expected, but I'm curious how to properly test it.

I could use real container instead of a mock, and verify that it resolves 2 different instances of the class, but I consider it not "pure" unit test, as it actually relies on the workings of external code (windsor container itself).

As I said, this is theoretical, so if it's needed or not is out of the scope of the question.

Answers


You just need an assertion that the implementation Foo was registered against the service IFoo that would be the pure test (Example using NSubstitute as I have not used moq for some time).

[ Test ]
public void Should_register_implemenation_of_Foo_for_service_IFoo()
{
    var container = Substitute.For<IWindsorContainer>();

    container.Register( Component.For<IFoo>().ImplementedBy<Foo>() );

    container.Received().Register( Arg.Is<IRegistration[]>(x => Test(x) ));

}

private bool Test(IRegistration[] registrations)
{
    var fooRegistration = (ComponentRegistration<IFoo>) registrations[ 0 ];

    return fooRegistration.Implementation == typeof(Foo);
}
public interface IFoo {}

public class Foo : IFoo {}

I know you have said that the question theoretical but it is important to ask the following question so that those new to TDD assume that you must do things this way.

Should a test dictate how a component achieves it's goal or should it just test that a component actually achieves it's goal?

IMO I feel that there is more value in writing an integration test that shows that the wire up is correct over making sure that certain methods are called on dependencies.


Need Your Help

Is there a way to specify a default property value in Spring XML?

java xml spring properties

We are using a PropertyPlaceholderConfigurer to use java properties in our Spring configuration (details here)

In Django ORM, A "Student - Course" Model design

database django django-models django-views pinax

I would like to design a model for an online private school in Django. It focuses on relation among Students, Tutors and Courses.