我怎么知道我的程序在单元测试环境下

Her*_* Yu 5 .net c# console unit-testing visual-studio

我有一个控制台应用程序。在发布环境中,此时它可以完美运行。在 IDE 调试环境中,我不想关闭控制台窗口,所以我添加了这个函数,并在我的程序的最后调用它。

[Conditional("DEBUG")]
public static void DebugWaitAKey(string message = "Press any key")
{
    Console.WriteLine(message);
    Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

当我调试程序时,它对我来说效果很好。但是通过单元测试,它在退出之前仍然等待一个键!

解决方法只是我的程序的单元测试发行版,或测试其他功能。但我确实想要一些可以识别当前会话正在进行单元测试的东西,并在这个函数中使用该标志。

小智 5

我相信应该能回答你的问题。我从那里上了一门课,并根据您的情况进行了调整。

/// <summary>
/// Detects if we are running inside a unit test.
/// </summary>
public static class UnitTestDetector
{
    static UnitTestDetector()
    {
        string testAssemblyName = "Microsoft.VisualStudio.QualityTools.UnitTestFramework";
    UnitTestDetector.IsInUnitTest = AppDomain.CurrentDomain.GetAssemblies()
        .Any(a => a.FullName.StartsWith(testAssemblyName));
    }

    public static bool IsInUnitTest { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我在您的方法中添加了一行,如果它正在运行测试,它将不会命中 Console.ReadKey();

[Conditional("DEBUG")]
public static void DebugWaitAKey(string message = "Press any key")
{
    Console.WriteLine(message);
    if(!UnitTestDetector.IsInUnitTest)
        Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

注意:这将被视为一种黑客行为,不会被视为最佳实践。

编辑: 我还在 github 上创建了一个示例项目来演示此代码。https://github.com/jeffweiler8770/UnitTest