如何解决Net Core Identity 不使用 InMemory 数据库
我正在为我的应用进行集成测试。我想在我的测试中使用 InMemory 数据库,所以我创建了 IntegrationTest 类,在那里我用我的 Web API 设置了我的 HttpClient:
public class IntegrationTest
{
protected readonly HttpClient TestClient;
protected Integrationtest()
{
Environment.SetEnvironmentvariable("ASPNETCORE_ENVIRONMENT","Staging");
Environment.CurrentDirectory = "C:\\Users\\adamg\\source\\repos\\CarShowroomApp\\CarShowroomBackEnd\\CarShowroomApp.UI\\";
var appFactory = new WebApplicationFactory<Startup>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services.RemoveAll(typeof(DatabaseContext<User,Role>));
services.AddDbContext<DatabaseContext<User,Role>>(options =>
options.UseInMemoryDatabase("xxx")
);
services.AddIdentity<User,Role>()
.AddRoles<Role>()
.AddEntityFrameworkStores<DatabaseContext<User,Role>>();
});
});
TestClient = appFactory.CreateClient();
}
protected async Task AuthenticateAsync()
{
TestClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer",await GetJwtAsync());
}
private async Task<string> GetJwtAsync()
{
var response = await TestClient.PostAsJsonAsync("api/auth/login",new UserForRegisterDto()
{
UserName = "TestUser123",Password = "#Mastercard1"
});
return (await response.Content.ReadAsAsync<AuthSuccessResponse>()).Token.ToString();
}
}
构建整个应用程序后,我从服务提供程序中删除了 DbContext (EF Core),并使用 InMemory Db 添加了新的。然后我添加身份(感谢“暂存”环境 - 构建时没有添加身份)。 尽管有这些操作,API 在测试期间仍然使用生产数据库:
public class CarControllerIntegrationTest : IntegrationTest
{
[Fact]
public async Task GetAllAsync_NoCars_OkObjectResultWithEmptyList()
{
await AuthenticateAsync();
var response = await TestClient.GetAsync("api/car/");
response.StatusCode.Should().Be(HttpStatusCode.OK);
(await response.Content.ReadAsAsync<PagedList<CarDto>>()).Should().BeEmpty();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。