In Castle Windsor 3, override an existing component registration in a unit test

前端 未结 2 671
自闭症患者
自闭症患者 2020-12-15 03:56

I am attempting to use Castle Windsor in my automated tests like so:

On every test:

  • The Setup() function creates a Windsor container, regi
相关标签:
2条回答
  • 2020-12-15 04:21

    There are two things that you have to do to create an overriding instance:

    1. Assign it a unique name
    2. Call the IsDefault method

    So to get the example to work:

    this.WindsorContainer.Register(
                                 Component.For<IMediaPlayerProxyFactory>()
                                          .Instance(mockMediaPlayerProxyFactory)
                                          .IsDefault()
                                          .Named("OverridingFactory")
                              );
    

    Because I plan to use this overriding patten in many tests, I've created my own extension method:

    public static class TestWindsorExtensions
    {
        public static ComponentRegistration<T> OverridesExistingRegistration<T>(this ComponentRegistration<T> componentRegistration) where T : class
        {
            return componentRegistration
                                .Named(Guid.NewGuid().ToString())
                                .IsDefault();
        }
    }
    

    Now the example can be simplified to:

    this.WindsorContainer.Register(
                                 Component.For<IMediaPlayerProxyFactory>()
                                          .Instance(mockMediaPlayerProxyFactory)
                                          .OverridesExistingRegistration()
                              );
    


    Later Edit

    Version 3.1 introduces the IsFallback method. If I register all my initial components with IsFallback, then any new registrations will automatically override these initial registrations. I would have gone down that path if the functionality was available at the time.

    https://github.com/castleproject/Windsor/blob/master/docs/whats-new-3.1.md#fallback-components

    0 讨论(0)
  • 2020-12-15 04:40

    Don't reuse your container across tests. Instead, set it to null in the TearDown() and re-initialise it for each actual test.

    0 讨论(0)
提交回复
热议问题