【问题标题】:Using Moq With Castle Windsor将起订量与温莎城堡一起使用
【发布时间】:2015-03-31 15:45:22
【问题描述】:

我正在尝试使用 Moq 对我的家庭控制器进行简单的单元测试,但我遇到了一个例外

“Castle.MicroKernel.ComponentNotFoundException”发生在 Castle.Windsor.dll 中,但未在用户代码中处理。未找到支持 OrderTrackingSystem.Core.Repositories.IRepository 服务的组件

在我的 HomeController 上就行了_repository = MvcApplication.Container.Resolve<IRepository>()

private IRepository _repository;
_repository = MvcApplication.Container.Resolve<IRepository>();

public HomeController(IRepository repository)
{
     _repository = repository;
}

这是我的单元测试代码。

[TestClass]
public class HomeControllerTests
{
    private Mock<IRepository> _repositoryMock;

    [TestInitialize]
    public void TestSetup()
    {
        _repositoryMock = new Mock<IRepository>();
    }

    [TestMethod]
    public void HomeControllerIndexReturnsAView()
    {
        // Arrange
        var controller = new HomeController(_repositoryMock.Object);

        // Act
        var result = controller.Index() as ViewResult;

        // Assert
        Assert.IsNotNull(result);
    }
}

我觉得在我的单元测试中注册或设置存储库时一定缺少一些简单的东西。有什么想法吗?

【问题讨论】:

  • 这样做public HomeController(IRepository repository) 的意义不是你不需要这样做_repository = MvcApplication.Container.Resolve&lt;IRepository&gt;() 因为你正在使用castle-windsor 进行构造函数注入...
  • 感谢您指出这一点。我继承了这段代码,但我仍在尝试找出 Castle。一旦我删除了它,单元测试就开始工作了,它似乎没有破坏应用程序中的任何其他内容。

标签: c# asp.net-mvc unit-testing moq castle-windsor


【解决方案1】:

我没有使用 Castle Windsor,但查看您的控制器,它似乎使用构造函数注入来提供控制器依赖项。这个tutorial 建议使用Windsor 的常用方法是创建一个从DefaultControllerFactory 派生的ControllerFactory,它在内部使用内核来解决控制器的依赖关系。这似乎证实了您代码中的这一行是多余的:

_repository = MvcApplication.Container.Resolve<IRepository>();

所以,你的代码应该是:

private IRepository _repository;

// The repository is being created + injected by Windsor.
// If this wasn't correctly wired up already, you'd be getting errors
// indicating that your HomeController didn't have a default constructor...
public HomeController(IRepository repository)
{
     _repository = repository;
}

一旦您删除了对 Resolve 的调用,您应该能够将模拟依赖项从您的单元测试中注入到您的类中,正如您所描述的那样。

虽然在某些情况下您可能需要从控制器工厂外部访问 Windsor 内核以解决依赖关系,但它们应该很少见。

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多