使用依赖注入的测试方法(结构图)

发布于 2024-12-08 12:05:16 字数 87 浏览 2 评论 0原文

我有一个工厂方法来创建某个接口的新实例。

我正在使用 StructureMap 创建接口的新实例。

我如何对该方法进行单元测试?

I have got a factory method that create new instances of a certain interface.

I am using StructureMap to create new instances of the interface.

How can I unit test this method?

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

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

发布评论

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

评论(2

能否归途做我良人 2024-12-15 12:05:16

如果你让工厂将 IContainer 作为 ctor 依赖项,你就可以删除该容器。

如果您配置 Structure Map 来实例化工厂,则 IContainer 应由 Structure Map 自动解析。

编辑:

我正在考虑这样的事情,在测试时将结构图从等式中剔除:

[Test]
public void ResolvesFooFromContainer()
{
   var expectedFoo = new Foo();
   var container = MockRepository.GenerateStub<IContainer>();
   container.Stub(c => c.GetInstance<Foo>()).Return(foo);
   var factory = new FooFactory(container);

   var createdFoo = factory.CreateFoo();

   Assert.That(createdFoo, Is.EqualTo(expectedFoo));
}

该示例使用Rhino Mocks和NUnit,但当然您可以以任何您想要的方式进行测试和存根。

If you make the factory take an IContainer as a ctor dependency you can stub out the container.

The IContainer should be resolved automatically by Structure Map if you configure Structure Map to instantiate the factory.

Edit:

I was thinking about something like this, taking Structure Map out of the equation when testing:

[Test]
public void ResolvesFooFromContainer()
{
   var expectedFoo = new Foo();
   var container = MockRepository.GenerateStub<IContainer>();
   container.Stub(c => c.GetInstance<Foo>()).Return(foo);
   var factory = new FooFactory(container);

   var createdFoo = factory.CreateFoo();

   Assert.That(createdFoo, Is.EqualTo(expectedFoo));
}

The example uses Rhino Mocks and NUnit, but of course you can test and stub any way you want.

旧瑾黎汐 2024-12-15 12:05:16

我终于能够实现我想要的了。

如果您考虑一下,您希望在隔离的环境中执行测试。

因此,我只需要使用模拟对象初始化结构,然后就可以测试我的工厂方法。

I was finally able to achieve what I wanted.

If you will think about it, you want to perform your test in an isolated environment.

So I just needed to initialise structure with a mock object and I was able to test my factory method.

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