如何在代码中告诉我们是否从testmethod .net测试运行

时间:2010-03-15 11:33:59

标签: c# .net testing

有没有办法知道何时通过运行测试方法调用代码?

bool MyMethod()
{
    if ( /* are we running a test? */ )
    {
        return true; // otherwise this will fail from the automated build script
    }
    else
    {
        // run the proper code
    } 
}
请告诉我“这是一个非常糟糕的主意”评论:))

6 个答案:

答案 0 :(得分:6)

你认识到这可能是一个坏主意,但你可能不知道其他选择。 您应该研究mocking frameworks - 它们可以提供一种在单元测试中在运行时将替代实现注入代码的方法。这是一种既定的做法,允许代码在测试中表现不同生产

关于主要问题。

这取决于您使用的单元测试框架。我不知道NUnit中的特定功能(例如)报告您正在测试中。其他框架(如MS Test)可能很好地提供了这一点。但是,你自己很容易做到。

如果你绑定了源代码,只需使用#define指令来有条件地定义一些你可以分支的变量。

如果您要绑定到库,我建议您创建自己的类,用于跟踪您是在单元测试还是实际代码中,并在{ {3}}表示您正在运行测试。您也可以使用TestFixture setup method作为避免编写特殊类的方法。

答案 1 :(得分:1)

好的,我会饶恕你的“这个 是一个非常糟糕的主意”评论。

您可以为方法提供参数bool isTestMode

答案 2 :(得分:1)

你应该通过反思来检查调用方法的属性!我不会提到这是一个床上的想法,因为你知道它,因为我看到了;)

答案 3 :(得分:1)

您的问题中概述的方法是一个非常糟糕的主意。

如果您希望方法在测试中的行为与其他方法不同,那么更简洁的方法是使用该方法重构接口,并在测试时注入不同的实现。

E.g:

// Interface whose implementation changes under testing
public interface IChangesUnderTest
{
  void DoesSomething();
}

// Inject this in production
public class ProductionCode : IChangesUnderTest
{
  void DoesSomething() { /* Does stuff */ }
}

// Inject this under test
public class TestCode : IChangesUnderTest
{
  void DoesSomething() { /* Does something else */ }
}

答案 4 :(得分:1)

这是我的建议。

不是检查上下文,只需添加一些条件错误代码:

#if DEBUG

/* assume you are running in a test environment here */

#endif

这几乎不错。如果它不完全符合您的需求,您可以查看#define - “TEST”,以了解您可能希望在常规调试期间不执行测试代码。

答案 5 :(得分:0)

如果您使用测试框架,并且知道 testAssemblyName ,则可以执行以下操作:

bool IsInUnitTest = AppDomain.CurrentDomain.GetAssemblies()
            .Any(a => a.FullName.StartsWith(testAssemblyName));

更具体地说,如果您使用NUnit,则

bool IsRunningFromNUnit =
           AppDomain.CurrentDomain.GetAssemblies().Any(
                a=> a.FullName.ToLowerInvariant().StartsWith("nunit.framework"));

如果您使用MSTest,则将 testAssemblyName 替换为相应的 AssemblyName ,也许是 Microsoft.VisualStudio.QualityTools.UnitTestFramework