首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >值不能为空。(参数'connectionString') Xunit测试

值不能为空。(参数'connectionString') Xunit测试
EN

Stack Overflow用户
提问于 2020-04-01 17:24:59
回答 1查看 575关注 0票数 0

我试图用Xunit编写单元测试:

代码语言:javascript
运行
复制
  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,它运行平稳,没有连接问题。

startup.cs:

代码语言:javascript
运行
复制
 services.AddDbContext<BlogProjectContext>(option =>
        option.UseSqlServer(Configuration.GetConnectionString("BlogProjectConnection"))
        );

appsetings.json:

代码语言:javascript
运行
复制
    {
  "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"

  }
}
EN

回答 1

Stack Overflow用户

发布于 2020-04-01 18:13:30

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

不过,您确实不希望单元测试发出真正的HTTP请求。解决这一问题的方法是模拟 HttpClient这里是一篇关于嘲弄HttpClient的有用博客文章。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60976761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档