测试类找不到连接字符串

本文关键字:字符串 连接 找不到 测试类 | 更新日期: 2023-09-27 18:03:12

我正在。net Core中编写一些集成测试,由于连接字符串返回null,我无法让测试运行。我在Startup.cs中的代码如下,并且我确实按照这些答案将appsettings.json复制到测试项目中。我错过了什么?

EDIT:我弄清楚了如何通过单元测试,并且环境被设置为生产,即使我在测试和主要项目中显式地将ASPNETCORE_ENVIRONMENT设置为development。我正在调试模式下构建。我不知道该把它放在哪里。无论哪种方式,它都应该拉入一个值而不是null——appsettings.development.jsonappsettings.production.json都有一个字符串,而通用的appsettings.json在下面(与开发相同)。

EDIT 2:测试项目似乎完全忽略了我设置的任何配置。不管我是否告诉它,它都在运行主项目的Startup。我删除了对它的所有引用,但它仍然试图运行它。

Startup.cs:

public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", true, true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("MyDatabase")));
}

appsettings.json:

{
  "ConnectionStrings": {
    "MyDatabase": "Server=localhost;Database=MyDevLocal;Trusted_Connection=True;"
  }
}

测试类找不到连接字符串

这对我有用

var builder = new WebHostBuilder() .UseStartup<Startup>() .UseSetting("ConnectionStrings:DefaultConnection", /*Your conn string*/)

  1. 安装NuGet包到您的测试项目,即Microsoft. entityframeworkcore . sqlserver和Microsoft。AspNetCore

  2. 复制粘贴(或新建)应用设置。

{
    "ConnectionStrings": {
        "YourConnection": "Data Source=.''SqlExpress;Initial Catalog=DatabaseName;Integrated Security=True;"
    }
}
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
    public class YourTestServicesShould
    {
        private YourContext _yourContext; //TODO DI
        public IConfigurationRoot Configuration { get; set; }
        [Fact]
        public void Save_WhenGivenAValidOrderItem()
        {
            //Arrange
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            Configuration = builder.Build();
            var optionsBuilder = new DbContextOptionsBuilder<_yourContext>();
            optionsBuilder.UseSqlServer(Configuration.GetConnectionString("YourConnection"));
            _yourContext= new YourContext(optionsBuilder.Options);
    ....
   }
}

我可以抱怨生活在软件开发的前沿,但我不会,因为我只是在做一个个人项目。我在我的API项目(引用实体框架)中没有设置连接字符串,所以这里有一个例子MyAPI项目对我有用。

  1. 整体解决方案文件夹为MyApi, src和test在同一级别。
  2. 然后创建项目test'MyApi。集成测试和复制应用设置。从src'MyApi到test'MyApi。IntegrationTests

然后您可以创建测试,如下所示:

using System;
using System.Threading.Tasks;
using Xunit;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Hosting;
using System.Text;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json;
using System.IO;
namespace Tests
{
    public class MyAPIRequestsShould
    {
        IWebHostBuilder _webHostBuilder;
        TestServer _host;
        HttpClient _client;
        public MyAPIRequestsShould()
        {
            string curDir = Directory.GetCurrentDirectory();
            _webHostBuilder = new WebHostBuilder().UseContentRoot(curDir).UseStartup<MyApi.Startup>();
            _host = new TestServer(_webHostBuilder);
            _client = _host.CreateClient();
        }
    private dynamic newTestRegistration(string mobileCountryCode = "44", string fullMobile = "447900123456", string firstName = "Scooby", string surname = "Doo", DateTime? registeredAt = null)
    {
        return new { mobileCountryCode = mobileCountryCode, fullMobile = fullMobile, firstName = firstName, surname = surname, registeredAt = (registeredAt == null ? DateTime.UtcNow : (DateTime)registeredAt) };
    }
        [Fact]
        public async Task Return422WhenCountryCodeTooLong() 
        {
            object requestData = newTestRegistration(mobileCountryCode);
            var content = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
            // Exercise the fluent validation
            var response = await _client.PostAsync("api/appusers/registration", content);
            Assert.Equal(422, (int) response.StatusCode);
        }
    }
}

我使用MyApi的Startup类来初始化主机,但关键是在测试构造函数中使用'UseContentRoot(curDir)'。在此之前,嫉妒。ContentRoot被设置为某个bin文件夹。现在它找到了应用程序的测试版本。我喜欢这样一个事实,即我可以通过更改连接字符串将它指向我的数据库的集成版本。

我不知道如何在Visual Studio中调试测试,所以作为奖励,它是:测试->调试->选定测试|所有测试

我也有同样的问题,并通过首先复制应用程序设置使其工作。Json文件到我的测试项目,并设置输出总是复制。然后在我的测试设置中,我做了以下操作:

 string curDir = Directory.GetCurrentDirectory();
        var builder = new ConfigurationBuilder()
            .SetBasePath(curDir)
            .AddJsonFile("appsettings.json");
        var webBuilder = new WebHostBuilder()
            .UseContentRoot(curDir).UseConfiguration(builder.Build())
            .UseStartup<Startup>();

        var server = new TestServer(webBuilder);
        _client = server.CreateClient();

复制粘贴你的应用程序。并确保在你的启动文件构造函数中有以下代码:

public Startup(IConfiguration configuration)
        {
           // Configuration = configuration;
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
                Configuration = builder.Build();
        }

我在asp.net Core 2.2中有类似的问题,我从Visual studio执行测试,配置文件缺失。显然,我需要设置appsettings的路径,但UseContentRoot()不适合我。我的解决方案是:

var configuration = new ConfigurationBuilder()
  .AddJsonFile(appSettingsPath)
  .Build();
var builder = new WebHostBuilder()
  .UseConfiguration(configuration)
  .UseStartup<Web.Startup>();