在 .NET Core 集成测试中查找我的 ConnectionString [英] Finding my ConnectionString in .NET Core integration tests

查看:23
本文介绍了在 .NET Core 集成测试中查找我的 ConnectionString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的 .NET Core 项目构建自动化集成测试.不知何故,我需要访问我的集成测试数据库的连接字符串.新的 .net 核心不再有 ConfigurationManager,而是注入了配置,但没有办法(至少我不知道)将连接字符串注入测试类.

I'm building automated integration tests for my .NET Core project. Somehow I need to get access to a connection string for my integration tests database. The new .net core no longer has the ConfigurationManager, instead configurations are injected, but there is no way (at least not that I know of) to inject the connection string to a test class.

在 .NET Core 中有什么方法可以在不向测试类中注入内容的情况下获取配置文件吗?或者,有没有办法让测试类可以将依赖项注入其中?

Is there any way in .NET Core that I can get at the configuration file without injecting something into a test class? Or, alternatively, is there any way that a test class can have dependencies injected into them?

推荐答案

.NET Core 2.0

创建一个新配置并为您的 appsettings.json 指定正确的路径.

Create a new configuration and specify the correct path for your appsettings.json.

这是我在所有测试中继承的 TestBase.cs 的一部分.

This is a part of my TestBase.cs which I inherit in all my tests.

public abstract class TestBase
{
    protected readonly DateTime UtcNow;
    protected readonly ObjectMother ObjectMother;
    protected readonly HttpClient RestClient;

    protected TestBase()
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();

        var connectionStringsAppSettings = new ConnectionStringsAppSettings();
        configuration.GetSection("ConnectionStrings").Bind(connectionStringsAppSettings);

        //You can now access your appsettings with connectionStringsAppSettings.MYKEY

        UtcNow = DateTime.UtcNow;
        ObjectMother = new ObjectMother(UtcNow, connectionStringsAppSettings);
        WebHostBuilder webHostBuilder = new WebHostBuilder();
        webHostBuilder.ConfigureServices(s => s.AddSingleton<IStartupConfigurationService, TestStartupConfigurationService>());
        webHostBuilder.UseStartup<Startup>();
        TestServer testServer = new TestServer(webHostBuilder);
        RestClient = testServer.CreateClient();
    }
}

这篇关于在 .NET Core 集成测试中查找我的 ConnectionString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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