Home > Software engineering >  Share context between unit test and web api in a C# project
Share context between unit test and web api in a C# project

Time:10-28

How can I share the context that the test project created while running with the context of the web api? If the web api creates its context from environment variable, that will be different to that the unit test project creates. (In addition, I concat a guid to the database name, so as each test class have different database name that can run asynchron.)

Thank you.

This is how web api creates context in Program.cs

var connectionString = Environment.GetEnvironmentVariable("ConnectionString");
builder.Services.AddDbContext<Context>(options =>
options.UseSqlServer(connectionString));

And this is how test project creates:

public TestBase()
    {
        var connectionString = Environment.GetEnvironmentVariable("ConnectionString");
        connectionString = connectionString.Replace("dbName", "dbName"   Guid.NewGuid());

        var options = new DbContextOptionsBuilder<Context>()
           .UseSqlServer(connectionString).Options;
        context = new Context(options);
        context.Database.Migrate();
    }

CodePudding user response:

What I did in the past is having it like:

internal ApplicationDbContext dbContext;

public BaseCoreTest()
{
    var builder = new ConfigurationBuilder()
      .SetBasePath(Directory.GetCurrentDirectory())
      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

    var dbContextOptions = new DbContextOptionsBuilder<ApplicationDbContext>().UseSqlServer(builder.Build()["ConnectionStrings:Default"]).Options;

    dbContext = new ApplicationDbContext(dbContextOptions);
}

CodePudding user response:

From the documentation Integration tests in ASP.NET Core > Inject mock services

Services can be overridden in a test with a call to ConfigureTestServices on the host builder. To inject mock services, the SUT must have a Startup class with a Startup.ConfigureServices method.

You can use ConfigureTestServices to override the context service like :

var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
    builder.ConfigureTestServices(services =>
    {
        services.AddDbContext<DemoContext>(options =>
            options.UseSqlServer("Server=localhost;..."));
    });
});

var client = application.CreateClient();
  • Related