如何识别我的代码何时在C#中测试?

如何识别我的代码何时在C#中测试?,c#,.net,testing,.net-core,xunit,C#,.net,Testing,.net Core,Xunit,我在测试控制器时遇到问题,因为在我的启动时有一些行在测试时为空,我想添加一个条件,仅当它不测试时才运行这些行 // Desired method that retrieves if testing if (!this.isTesting()) { SwaggerConfig.ConfigureServices(services, this.AuthConfiguration, this.ApiMetadata.Version); } 这实际上取决于您用于测试的框架。它可以是MSTest、N

我在测试控制器时遇到问题,因为在我的启动时有一些行在测试时为空,我想添加一个条件,仅当它不测试时才运行这些行

// Desired method that retrieves if testing
if (!this.isTesting())
{
  SwaggerConfig.ConfigureServices(services, this.AuthConfiguration, this.ApiMetadata.Version);
}

这实际上取决于您用于测试的框架。它可以是MSTest、NUnit或其他什么

经验法则是,您的应用程序不应该知道它是否经过测试。这意味着在通过注入接口进行实际测试之前,应该对所有内容进行配置。测试应如何进行的简单示例:

//this service in need of tests. You must test it's methods.
public class ProductionService: IProductionService
{
    private readonly IImSomeDependency _dep;
    public ImTested(IImSomeDependency dep){ _dep = dep; }
    public void PrintStr(string str)
    {
        Console.WriteLine(_dep.Format(str));
    }
}

//this is stub dependency. It contains anything you need for particular test. Be it some data, some request, or just return NULL.
public class TestDependency : IImSomeDependency
{
    public string Format(string str)
    {
        return "TEST:"+str;
    }
}

//this is production, here you send SMS, Nuclear missle and everything else which cost you money and resources.
public class ProductionDependency : IImSomeDependency
{    
    public string Format(string str)
    {
        return "PROD:"+str;
    }
}
当您运行测试时,您可以这样配置系统:

var service = new ProductionService(new TestDependency());
service.PrintStr("Hello world!");
当您运行生产代码时,您可以按如下方式对其进行配置:

var service = new ProductionService(new ProductionDependency());
service.PrintStr("Hello world!");
这样,ProductionService只是在做他的工作,不知道它的依赖项中有什么,不需要“它是测试用例吗?”№431“国旗。 请尽可能不要在代码中使用测试环境标志

更新

有关如何更好地理解依赖关系管理,请参见@Mario\u The\u Spoon解释。

正确答案(尽管没有帮助):它应该不能告诉你。如果应用程序在productino或test中,那么它应该对它所做的一切进行检查

但是,要在更简单的设置中测试应用程序,可以使用加载的假模块或实体模型模块,而不是重型生产模块

但为了使用它,您必须重构您的解决方案,例如使用注入

我发现了一些链接:


请将您尝试过的所有内容添加到您的问题中,并说明它到底是如何失败的。请阅读您可以使用app.config文件中的设置吗?或者,如果您使用内存数据库进行测试,您可以检查它是否为空。这有点棘手,但不知道您的确切设置……我将添加您的答案,作为对示例的全面解释=)