views:

37

answers:

1

I am trying to use Castle Windsor with MS Test. The test class only seems to use the default constructor. How do I configure Castle to resolve the service in the constructor?

Here is the Test Class' constructors:

private readonly IWebBrowser _browser;

        public DepressionSummaryTests()
        {

        }

        public DepressionSummaryTests(IWebBrowser browser)
        {
            _browser = browser;
        }

My component in the app config looks like so:

 <castle>
    <components>
      <component id="browser"
                 service="ConversationSummary.IWebBrowser, ConversationSummary"
                 type="ConversationSummary.Browser" />       

    </components>
  </castle>

Here is my application container:

public class ApplicationContainer : WindsorContainer
    {
        private static IWindsorContainer container;

        static ApplicationContainer()
        {
            container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
        }
        private static IWindsorContainer Container
        {
            get { return container; }
        }

        public static IWebBrowser Browser
        {
            get { return (IWebBrowser) Container.Resolve("browser"); }
        }
    }

MS test requires the default constructor. What am I missing?

Thanks!

+1  A: 

Since MSTest requires the default constructor it also means that it only uses this constructor. Thus, you can never get it to use the overloaded constructor. That's not an issue with Castle Windsor, but just the way MSTest works.

It's not that big of a deal though, because you shouldn't need to use a container for unit testing anyway.

When you use Windsor, you may want to consider using the Fluent Registration API instead of XML.

Another thing is that you shouldn't use a static Service Locator - it's an anti-pattern. This means that the ApplicationContainer class is redundant and should be deleted.

Mark Seemann
100% agree. Requiring a DI container in your unit tests in oxymoron as you need to be able to instantiate and mock individual classes.
Igor Zevaka
I would agree typically. But in this case the service is a browser object that is used for UI testing. This coupling is unavoidable.
Nick