Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 值不能为null。(参数和连接字符串和)Xunit测试_Unit Testing_Asp.net Core Webapi_Xunit_Xunit.net_Webapi - Fatal编程技术网

Unit testing 值不能为null。(参数和连接字符串和)Xunit测试

Unit testing 值不能为null。(参数和连接字符串和)Xunit测试,unit-testing,asp.net-core-webapi,xunit,xunit.net,webapi,Unit Testing,Asp.net Core Webapi,Xunit,Xunit.net,Webapi,我正试图用Xunit编写单元测试: public class UserTest { private readonly TestServer _server; private readonly HttpClient _client; public UserTest() { _server = new TestServer(new WebHostBuilder().UseStartup<Startup>()); _c

我正试图用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);
    }
}

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


但是,您确实不希望单元测试发出真正的HTTP请求。解决这个问题的方法是使用
HttpClient
在你的链接中,这是一篇关于模仿
HttpClient

的有用博文,代码var subjectiondertest=newmytestclass(HttpClient);MyTestClass是什么意思?
 services.AddDbContext<BlogProjectContext>(option =>
        option.UseSqlServer(Configuration.GetConnectionString("BlogProjectConnection"))
        );
    {
  "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"

  }
}