NUnit集成测试和依赖项注入 [英] NUnit integration tests and dependency injection

查看:122
本文介绍了NUnit集成测试和依赖项注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Castle Windsor 2.1版作为我的容器,并希望使用向其注册的服务执行集成测试。

I'm currently making use of Castle Windsor version 2.1 as my container and would like to perform integration tests using the services registered with it.

当前,我正在我可以使用通用服务定位器来检索我的服务实例并对其进行集成测试,例如:

Currently, I do this my using the Common Service Locator to retrieve my service instance and perform my integration tests against it as such:

var myService = ServiceLocator.Current.GetInstance<IMyService>();
// do stuff with myService

我理想的情况是服务依赖项自动注入到我的NUnit测试装置中。 Spring似乎提供了此功能,但我不能

What I'd ideally like to do is have my service dependencies injected into my NUnit test fixture automatically. Spring seems to offer this functionality, but I can't locate anything similar using Castle.

有人可以指出我正确的方向吗?

Can anyone point me in the right direction?

编辑:

我确信每个人都(有效)对这是否是一个好主意要点;我们只是假设它处于这种情况下...谁能告诉我如何使用Windsor来完成 吗?

I'm sure everyone has (valid) points on whether or not this is a good idea; let's just assume that it is in this scenario...Can anyone tell me how this could be accomplished using Windsor?

推荐答案

如果您从Spring / Spring.net来到温莎,您会发现这些项目在很多方面没有达成共识。这就是其中之一。作为温莎的拥护者,我从不使用像Spring的AbstractDependencyInjectionSpringContextTests这样的东西。将事物注入测试似乎是错误的,但是再说一次,就像我说的那样,我有偏见。

If you're coming to Windsor from Spring/Spring.net you'll find that there are a number of things these projects don't agree on. This is one of them. As a Windsor advocate, I'd never use something like Spring's AbstractDependencyInjectionSpringContextTests. Injecting things into a test just seems wrong, but then again, like I said, I'm biased.

如果要进行集成测试,只需创建一个新的容器实例,添加所需的任何组件,然后运行要测试的任何组件,例如:

If you want to do an integration test, just create a new container instance, add whatever components you need, and run whatever you want to test, e.g:

[Test]
public void TestComponentThatDependsOnA() {
  var container = new WindsorContainer();
  container.Register(Component.For<MyComponentA>());
  container.Register(Component.For<ComponentThatDependsOnA>());
  var a = container.Resolve<ComponentThatDependsOnA>();
  var result = a.DoSomething();
  Assert.AreEqual("ok", result);
}

如果您的注册内容整齐地包裹在安装程序(您应该如此),您可以在测试中重复使用它们,从而使测试更加简洁。

If you have registrations neatly wrapped in installers (as you should) you can reuse them in your tests, making tests more concise.

如果您具有XML配置,则可以使用Configuration.FromXmlFile()轻松加载它。

If you have XML config, you can easily load it with Configuration.FromXmlFile().

此外,也无需使用Common这里的服务定位器。

Also, there is no need to use Common Service Locator here.

自动模拟容器,它将自动模拟服务(当然,除非您用具体的服务覆盖它们)。

Also useful for some integration tests is an auto-mocking container, which will automatically mock out services (unless you override them with concrete ones, of course).

这篇关于NUnit集成测试和依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆