使用NUnit进行MEF和单元测试 [英] MEF and unit testing with NUnit

查看:129
本文介绍了使用NUnit进行MEF和单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几周前,我跳上了MEF(ComponentModel)潮流,现在将其用于许多插件和共享库.总体而言,除了我经常犯的错误之外,这是很棒的事情,这会导致调试会话令人沮丧.

A few weeks ago I jumped on the MEF (ComponentModel) bandwagon, and am now using it for a lot of my plugins and also shared libraries. Overall, it's been great aside from the frequent mistakes on my part, which result in frustrating debugging sessions.

无论如何,我的应用程序运行良好,但是与MEF相关的代码更改导致我的自动构建失败.我的大多数单元测试都失败了,仅仅是因为我正在测试的模块依赖于需要由MEF加载的其他模块.我通过绕过MEF并直接实例化这些对象来解决这些情况.

Anyhow, my app has been running great, but my MEF-related code changes have caused my automated builds to fail. Most of my unit tests were failing simply because the modules I was testing were dependent upon other modules that needed to be loaded by MEF. I worked around these situations by bypassing MEF and directly instantiating those objects.

换句话说,通过MEF,我会得到类似的东西

In other words, via MEF I would have something like

[Import]
public ICandyInterface ci { get; set; }

[Export(typeof(ICandyInterface))]
public class MyCandy : ICandyInterface
{
    [ImportingConstructor]
    public MyCandy( [Import("name_param")] string name) {}
    ...
}

但是在我的单元测试中,我只会使用

But in my unit tests, I would just use

CandyInterface MyCandy = new CandyInterface( "Godiva");

此外,CandyInterface需要与数据库建立连接,而我只是通过将测试数据库添加到我的单元测试文件夹中来解决此问题,我让NUnit在所有测试中都使用了该数据库.

In addition, the CandyInterface requires a connection to a database, which I have worked around by just adding a test database to my unit test folder, and I have NUnit use that for all of the tests.

好的,这是我关于这种情况的问题:

Ok, so here are my questions regarding this situation:

  1. 这是做事的坏方法吗?
  2. 建议您在[设置]中组成零件
  3. 我尚未学习如何在单元测试中使用模拟-这是一个很好的例子,我可能想要模拟基础数据库连接(以某种方式)以仅返回虚拟数据而实际上并不需要数据库?
  4. 如果您之前遇到过类似情况,能否提供您的经验以及解决问题的方式? (还是应该进入社区Wiki?)

推荐答案

听起来您在正确的轨道上.单元测试应该测试一个单元,这就是您直接创建实例时要做的.如果让MEF为您组成实例,则它们倾向于进行集成测试.集成测试并不是说有什么问题,但是单元测试往往更易于维护,因为您可以单独测试每个单元.

It sounds like you are on the right track. A unit test should test a unit, and that's what you do when you directly create instances. If you let MEF compose instances for you, they would tend towards integration tests. Not that there's anything wrong with integration tests, but unit tests tend to be more maintainable because you test each unit in isolation.

在单元测试中不需要容器来连接实例.

我通常建议不要在SetUp中编写夹具,因为它会导致通用夹具反模式.

I generally recommend against composing Fixtures in SetUp, as it leads to the General Fixture anti-pattern.

最佳做法是将依赖关系替换为测试双打.动态模拟是执行此操作的一种更通用的方法,因此绝对应该学习一些东西.

It is best practice to replace dependencies with Test Doubles. Dynamic mocks is one of the more versatile ways of doing this, so definitely something you should learn.

这篇关于使用NUnit进行MEF和单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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