我目前正在尝试为.NET Core 2.2 API设置集成测试。每当我运行测试时,都会出现以下错误:
Message: System.NullReferenceException : Object reference not set to an instance of an object.
我已经搜索过,但找不到任何有关此内容或为何收到此错误的信息。
这是我的测试UsersIntegrationTests类,该错误告诉我在方法开始时此行中出现空引用异常:“公共异步任务Test1Async(string方法)”
我对此一无所知,而且我对.NET Core相对陌生。这可能是一个漫长的过程,但是如果有人以前遇到过这个问题并且知道如何解决它,并且可以解释一下如何使这些测试运行?
public class UsersIntegrationTests
{
private readonly HttpClient _client;
private readonly TestServer _server;
public UsersIntegrationTests()
{
_server = new TestServer(new WebHostBuilder()
.UseEnvironment("Development")
.UseStartup<Startup>());
_client = _server.CreateClient();
}
[Theory]
[InlineData("GET")]
public async Task Test1Async(string method)
{
var request = new HttpRequestMessage(new HttpMethod(method), "/api/values");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
我的startup.cs类:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TestDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// Get information from the app settings and make use of it
var appSettingsSection = Configuration.GetSection("AppSecrets");
services.Configure<AppSecrets>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSecrets>();
//string connection = appSettings.ConnectionString;
//services.AddDbContext<TestDBContext>(options => options.UseSqlServer("Server=DESKTOP-F9KBARO;Database=TestDB;Trusted_Connection=True;MultipleActiveResultSets=True"));
var key = Encoding.UTF8.GetBytes(appSettings.Secret);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://localhost:52459",
ValidAudience = "http://localhost:52459",
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
services.AddCors(options =>
{
options.AddPolicy("AllowAll", p =>
{
p.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
DependencyInjectionConfig.AddScope(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<Data.Models.UserForCreationDto, Data.Entities.AppUser>();
});
//app.ConfigureCustomExceptionMiddleware();
app.UseCors("AllowAll");
app.UseHttpsRedirection();
app.UseMvc();
}
}