Unit testing 值不能为null。(参数和连接字符串和)Xunit测试
我正试图用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
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"
}
}