5

I'm trying to accomplish a seemingly super simple thing: from my unit test I want to replace the type being resolved with a mock/fake object.

For example: the xml config states that a component of the service IInterface should resolve to ClassA. That's fine, but from my unit test I want the type to resolve to FakeClassA instead. I can't use container.AddComponent for this, since there "is a component already registered for the given key ...".

Peter Evjan
  • 2,423
  • 3
  • 32
  • 50
  • See also: How are components removed with Castle 3.0? http://stackoverflow.com/questions/9501209/how-are-components-removed-with-castle-3-0 – Anthony Jan 17 '13 at 11:30

1 Answers1

4

IKernel has a RemoveComponent method.

But for unit tests it's recommended that you don't use the container at all, or if the test setup gets too dense because of dependencies, use an AutoMockingContainer.

Here's another (more updated) implementation.

Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275
  • RemoveComponent states "Returns true if the specified component was found and could be removed (i.e. no other component depends on it)". But what if we dont care if something else depends upon it, as we are going to replace it in the next line of code. – crowleym Jun 04 '09 at 11:22
  • You can't. Removing components from the container is *not* a normal usage in Windsor. – Mauricio Scheffer Jun 04 '09 at 12:39
  • Mauricio Scheffer: You have a dead link – Anthony Dec 16 '09 at 19:55
  • @kappasims : I did fix it back in '09 but it seems the repo was deleted. Fixed again. Also, please instead of just saying "still dead" post a new repo, thanks. – Mauricio Scheffer May 10 '12 at 18:09
  • 4
    RemoveComponent method has been removed From Windsor Castle 3 – VdesmedT Jun 29 '12 at 12:23
  • @MauricioScheffer Why it is not normal to remove components from windsor? Also, is it quite a generic statement applicable to all IoC containers like Unity, autofac etc? Generally we register all the dependencies at the start-up of the application. I'm needing this registration/de-registration of dependencies only in the case of unit test cases which run one after the other. – RBT Mar 14 '16 at 12:46
  • @RasikBihariTiwari Yes, this generalizes to all containers. IoC containers are bad enough as they are. If you start removing components you're making things even more mutable so harder to reason about. – Mauricio Scheffer Mar 14 '16 at 14:49