使用 Ninject 解决 Asp.Net MVC 单元测试中的控制器构造函数依赖关系

发布于 2024-12-18 17:55:03 字数 646 浏览 1 评论 0原文

我不确定如何使用 Ninject 在单元测试中自动解决控制器的构造函数依赖关系。

在我的实际应用程序中,我在 gloabl.asax 中设置了依赖注入,如下所示:

public void SetupDependencyInjection()
    {
        IKernel kernel = new StandardKernel();

        kernel.Bind<ISomeService>().To<SomeService>();

        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }

我有一个带有构造函数的控制器:

public SomeController (ISomeService someService)

这一切都工作正常,不知何故神奇的是,SomeController 构造函数被以 someService 作为参数调用。但我不知道如何在单元测试中复制这种行为。也就是说,我想配置我的单元测试,这样我就不必自己通过构造函数创建控制器 - 我希望 ninject 以与实际应用程序中相同的方式执行此操作。

感谢您提前提供任何帮助!

I am unsure how to use Ninject to automatically resolve constructor dependencies for my controllers in my unit tests.

In my actual application I have setup my dependency injection in my gloabl.asax as follows:

public void SetupDependencyInjection()
    {
        IKernel kernel = new StandardKernel();

        kernel.Bind<ISomeService>().To<SomeService>();

        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }

I have a contoller with a constructor:

public SomeController (ISomeService someService)

This all works fine, somehow magically the SomeController constructor gets called with someService as an argument. I have no idea how I would replicate this behaviour in my unit tests though. That is, I would like to configure my unittests so that I don't have to create my controllers via the constructor myself - I'd like ninject to do this in much the same way it does it in the real application.

Thanks for any help in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

往事随风而去 2024-12-25 17:55:03

我不知道如何在单元测试中复制这种行为

在单元测试中,您可以使用模拟框架,例如 Rhino MocksMoq 为您的依赖项生成模拟对象,并定义对他们的期望。

Rhino Mocks 示例:

[TestMethod]
public void Test_Something()
{
    // arrange
    var serviceMock = MockRepository.GenerateStub<ISomeService>();
    serviceMock.Stub(x => x.SomeMethod(123)).Return("foo bar");
    var sut = new SomeController(serviceStub);

    // act
    var actual = sut.SomeAction();

    // assert
    // TODO: assert on the result
}

I have no idea how I would replicate this behaviour in my unit tests though

In your unit test you could use a mocking framework such as Rhino Mocks or Moq to generate mock objects for your dependencies and define expectations on them.

Example with Rhino Mocks:

[TestMethod]
public void Test_Something()
{
    // arrange
    var serviceMock = MockRepository.GenerateStub<ISomeService>();
    serviceMock.Stub(x => x.SomeMethod(123)).Return("foo bar");
    var sut = new SomeController(serviceStub);

    // act
    var actual = sut.SomeAction();

    // assert
    // TODO: assert on the result
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文