确定代码运行作为单元测试的一部分 [英] Determine if code is running as part of a unit test

查看:103
本文介绍了确定代码运行作为单元测试的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单元测试(NUnit的)。许多层向下调用堆栈,如果它是通过单元测试运行的方法将失败。

I have a unit test (nUnit). Many layers down the call stack a method will fail if it is running via a unit test.

在理想情况下,你会使用类似嘲讽设置,这种方法是根据不同的对象。关于但这是第三方代码,我不能这样做,如果没有大量的工作。

Ideally you would use something like mocking to setup the object that this method is depending on but this is 3rd party code and I can't do that without a lot of work.

我不希望安装NUnit的具体方法 - 有太多的水平这里和做单元测试的一个好办法。

I don't want setup nUnit specific methods - there are too many levels here and its a poor way of doing unit test.

相反,我想要做的就是在调用栈

Instead what I would like to do is to add something like this deep down in the call stack

#IF DEBUG // Unit tests only included in debug build
if (IsRunningInUnitTest)
   {
   // Do some setup to avoid error
   }
#endif

因此,任何想法左右如何写IsRunningInUnitTest?

So any ideas about how to write IsRunningInUnitTest?

PS我深知,这不是伟大的设计,但我的认为的它比其它更好。

P.S. I am fully aware that this is not great design, but I think its better than the alternatives.

推荐答案

我已经这样做过 - 我只好抱着我的鼻子,而我做到了,但我做到了。实用主义次教条主义每次。当然,如果有的可重构,以避免它一个很好的方法,这将是巨大的。

I've done this before - I had to hold my nose while I did it, but I did it. Pragmatism beats dogmatism every time. Of course, if there is a nice way you can refactor to avoid it, that would be great.

基本上,我有一个UnitTestDetector类检查NUnit的框架组件是否在当前的AppDomain加载。它只需做一次,然后缓存结果。难看,但简单而有效的。

Basically I had a "UnitTestDetector" class which checked whether the NUnit framework assembly was loaded in the current AppDomain. It only needed to do this once, then cache the result. Ugly, but simple and effective.

这篇关于确定代码运行作为单元测试的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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