[英]ASP.NET Core 7 WebApplicationFactory Integration tests. How to load data?
I am creating an integration test to check that the data is working based on this very good tutorial.我正在创建一个集成测试,以根据这个非常好的教程检查数据是否正常工作。
The tutorial loads sample data in the OnModelCreating.本教程在 OnModelCreating 中加载示例数据。 But I was unsure if doing that will repeatedly load data to the DB when running the program.但是我不确定这样做是否会在运行程序时重复将数据加载到数据库中。
However although I can get the index page to load, it has the page content, such as the table structure for the data it doesn't have the data from the database.但是,尽管我可以加载索引页面,但它具有页面内容,例如数据的表结构,它没有数据库中的数据。
Using Swagger I copied a sample of data as JSON, saved it to a file, capitalized the first letter of the key to make it the same as the properties (after not doing do was fruitless as well), and tried to add it to the context.使用 Swagger 我复制了一个数据样本作为 JSON,将其保存到一个文件中,将密钥的第一个字母大写以使其与属性相同(不这样做之后也没有结果),并尝试将其添加到语境。
internal static class AddTestData
{
//import json array and add to context
public static void AddMovieData(ApplicationDbContext context)
{
var jsonString = File.ReadAllText("testMoviedata.json");
var list = JsonSerializer.Deserialize<List<Movie>>(jsonString);
{
foreach (var item in list)
{
context.Movie.Add(item);
}
context.SaveChanges();
}
}
}
and tried to add it to the dbcontext in this process in the WebApplicationFactory Class from HERE并尝试将其添加到 WebApplicationFactory Class 中此过程中的 dbcontext 来自HERE
public class TestingWebAppFactory<TEntryPoint> : WebApplicationFactory<Program> where TEntryPoint : Program
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
......... stuff deleted for brevity... .........为简洁起见删除了内容......
using (var appContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>())
{
try
{
appContext.Database.EnsureCreated();
// Seed the database with test data.
AddTestData.AddMovieData(appContext);
}
catch (Exception ex)
{
//Log errors or do anything you think it's needed
throw;
}
}
... still nothin. ...仍然没有。 Page loads, no data loads.页面加载,没有数据加载。
Also why can't I get breakpoints to work in the Integration project?另外,为什么我不能在 Integration 项目中使用断点?
What am I doing wrong?我究竟做错了什么?
Solved!!!解决了!!!
The code was OK,but the data wasn't being deserialised.代码没问题,但数据没有被反序列化。
I had to move it to the main project and test it there.我不得不将它移动到主项目并在那里进行测试。
The solution is解决办法是
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var list = JsonSerializer.Deserialize<Movie[]>(jsonString, options);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.