How can I unit test that Windsor can resolve Asp.net MVC3 controller dependencies?
Asked Answered
R

1

6

Currently I have Windsor controller factory that is working well. However, I am changing my controllers a bit and having Windsor instantiate more data for controllers. I forgot to update my Installer class and it failed.

Thus, I realized this is a perfect instance for unit testing, so every time I run my unit tests it will verify that Windsor is set up correctly.

Thus I created the following unit test:

    [TestMethod]
    public void Windsor_Can_Resolve_HomeController_Dependencies()
    {
        // Setup
        WindsorContainer container = new WindsorContainer();

        // Act
        HomeController controller = (HomeController)container.Kernel.Resolve(typeof(HomeController));
    }

This is exactly the same code that exists in my WindsorControllerFactory.GetControllerInstance() method so I am not sure why this isn't working. When this runs I get:

Test method MyApp.Tests.Controllers.HomeControllerTest.Windsor_Can_Resolve_HomeController_Dependencies threw exception: 
Castle.MicroKernel.ComponentNotFoundException: No component for supporting the service MyApp.Controllers.HomeController was found

I'm not sure how to tackle this. The only thing I can think of is that since it's in my test project, and not my Asp.net MVC project it might not be automatically picking up my CommandAndQueryInstaller class, which contains all of my windsor type registration.

Any advice for unit testing windsor dependency configuration?

Rancourt answered 8/4, 2011 at 23:13 Comment(1)
The questioner has asked a question that follows this one if you're using the PerWebResquestLifeStyle: https://mcmap.net/q/667411/-how-can-i-unit-test-my-controller-to-make-sure-windsor-can-resolve-dependencies-when-using-perwebrequestlifestyle/114029 Make sure you check it.Methacrylate
E
7

You are creating a new WindsorContainer in your setup and not registering any dependencies in the container. You'll need to run your IWindsorInstallers in order to populate the container.

[TestMethod]
public void Windsor_Can_Resolve_HomeController_Dependencies()
{
    // Setup
    WindsorContainer container = new WindsorContainer();
    container.Install(FromAssembly.Containing<HomeController>());

    // Act
    HomeController controller = container.Resolve<HomeController>();
}

Note that you don't have to access the kernel. You can use container.Resolve<T>(), which also takes care of the cast internally.

Ethno answered 8/4, 2011 at 23:35 Comment(1)
Aha, I knew I was looking for something like that, I just couldn't find it in my code base. Thanks!Rancourt

© 2022 - 2024 — McMap. All rights reserved.