Search code examples
asp.net-coreintegration-testing

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. 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.

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

 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?

What am I doing wrong?


Solution

  • 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);