1

我正在努力对以下代码进行单元测试。它是用于在应用程序中初始化 mvc 控制器的控制器工厂。谁能给我一些关于如何进行单元测试的指示?

public class WindsorControllerFactory : DefaultControllerFactory
{
    private readonly IKernel kernel;

    public WindsorControllerFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public override void ReleaseController(IController controller)
    {
        this.kernel.ReleaseComponent(controller);
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
        }

        return (IController)this.kernel.Resolve(controllerType);
    }
}
4

1 回答 1

0

unless you decide to override

IController CreateController(RequestContext requestContext, string controllerName)

your test become more complex because original CreateController calls GetControllerType

Said so, I have to agree with Ales... but if you really have to... you can easly unit test kernel invocation using a mocking framework such Moq

Let say you want test ReleaseController method

var controller = new Mock<IController>();
var kernel= new Mock<IKernel>();
var windsorControllerFactory = new WindsorControllerFactory(kernel.Object);
windsorControllerFactory.ReleaseController(controller.Object);
kernel.Verify(m => m.ReleaseComponent(controller.Object));
于 2013-09-27T09:06:07.820 回答