【问题标题】:Value cannot be null. (Parameter 'connectionString') Xunit test值不能为空。 (参数'connectionString') Xunit 测试
【发布时间】:2020-04-01 17:24:59
【问题描述】:

我正在尝试用 Xunit 编写单元测试:

  public class UserTest
{

    private readonly TestServer _server;
    private readonly HttpClient _client;

    public UserTest()
    {
        _server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
        _client = _server.CreateClient();
    }

    [Fact]
    public async Task GetAllUserTest()
    {
        var request = new HttpRequestMessage(new HttpMethod("Get"), "/Api/Users");

        var response =await _client.SendAsync(request);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
}

请求验证在我的解决方案中。 测试运行后,测试失败,消息错误为:

值不能为空。 (参数'connectionString')

如果我运行api,它运行顺利,没有CONNECTION问题。

startup.cs:

 services.AddDbContext<BlogProjectContext>(option =>
        option.UseSqlServer(Configuration.GetConnectionString("BlogProjectConnection"))
        );

appsettings.json:

    {
  "AppSettings": {
    "Secret": "This is the secret key and its very important"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "BlogProjectConnection": "Data Source=.;Initial Catalog=BlogProject_DB;Integrated Security=True"

  }
}

【问题讨论】:

    标签: unit-testing asp.net-core-webapi xunit xunit.net webapi


    【解决方案1】:

    我假设您的单元测试与您的 API 位于不同的项目中?您的单元测试项目在与您的 API 不同的目录中运行,因此它们无法“看到”您的 API 可以看到的 appsettings.json 文件,从而导致您看到此错误。

    你真的不希望你的 unit 测试发出真正的 HTTP 请求。对此的补救措施是mockHttpClientHere 是一篇关于嘲笑 HttpClient 的有用博文。

    【讨论】:

    • 在您的链接中,此代码 var subjectUnderTest = new MyTestClass (httpClient); MyTestClass 是什么意思?
    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多