Reconfigure dependencies when testing integration of ASP.NET Core Web API and EF Core

I am following this tutorial
Integration Testing with Entity Framework Core and SQL Server

My code looks like this

Integration Test Class

public class ControllerRequestsShould : IDisposable
{
    private readonly TestServer _server;
    private readonly HttpClient _client;
    private readonly YourContext _context;

    public ControllerRequestsShould()
    {
        // Arrange
        var serviceProvider = new ServiceCollection()
            .AddEntityFrameworkSqlServer()
            .BuildServiceProvider();

        var builder = new DbContextOptionsBuilder<YourContext>();

        builder.UseSqlServer($"Server=(localdb)\\mssqllocaldb;Database=your_db_{Guid.NewGuid()};Trusted_Connection=True;MultipleActiveResultSets=true")
            .UseInternalServiceProvider(serviceProvider);

        _context = new YourContext(builder.Options);
        _context.Database.Migrate();

        _server = new TestServer(new WebHostBuilder()
            .UseStartup<Startup>()
            .UseEnvironment(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")));
        _client = _server.CreateClient();
    }

    [Fact]
    public async Task ReturnListOfObjectDtos()
    {
        // Arrange database data
        _context.ObjectDbSet.Add(new ObjectEntity{ Id = 1, Code = "PTF0001", Name = "Portfolio One" });
        _context.ObjectDbSet.Add(new ObjectEntity{ Id = 2, Code = "PTF0002", Name = "Portfolio Two" });

        // Act
        var response = await _client.GetAsync("/api/route");
        response.EnsureSuccessStatusCode();


        // Assert
        var result = Assert.IsType<OkResult>(response);            
    }

    public void Dispose()
    {
        _context.Dispose();
    }

As far as I understand, the method .UseStartUpguarantees that it TestServeruses my launch class

My problem is that when my law act

var response = await _client.GetAsync("/api/route");

I get an error in my startup class that the connection string is empty. I think my understanding of the problem is that when my controller gets access from the client, it deploys my data repository, which in turn enters the database context.

, new WebHostBuilder new WebHostBuilder , . , .

ConfigureServices Startup.cs

        public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services
        services.AddMvc(setupAction =>
        {
            setupAction.ReturnHttpNotAcceptable = true;
            setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
            setupAction.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());
        });

        // Db context configuration
        var connectionString = Configuration["ConnectionStrings:YourConnectionString"];
        services.AddDbContext<YourContext>(options => options.UseSqlServer(connectionString));

        // Register services for dependency injection
        services.AddScoped<IYourRepository, YourRepository>();
    }
+13
2

:

1. WebHostBuilder.ConfigureServices

, - WebHostBuilder.ConfigureServices WebHostBuilder.UseStartup<T> WebHostBuilder.UseStartup<T> DI -:

_server = new TestServer(new WebHostBuilder()
    .ConfigureServices(services =>
    {
        services.AddScoped<IFooService, MockService>();
    })
    .UseStartup<Startup>()
);

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        //use TryAdd to support mocking the service
        services.TryAddTransient<IFooService, FooService>();
    }
}

TryAdd Startup. WebHostBuilder.ConfigureServices Startup, , . TryAdd , , .

: ASP.NET.

2. / Startup

TestStartup ASP.NET Core DI. Startup :

public class TestStartup : Startup
{
    public TestStartup(IHostingEnvironment env) : base(env) { }

    public override void ConfigureServices(IServiceCollection services)
    {
        //mock DbContext and any other dependencies here
    }
}

, TestStartup , TestStartup .

UseStartup :

_server = new TestServer(new WebHostBuilder().UseStartup<TestStartup>());

: asp.net .

+17

@ilya-chumakov .

3. ConfigureTestServices WebHostBuilderExtensions.

ConfigureTestServices Microsoft.AspNetCore.TestHost 2.1 (20.05.2018 RC1-). .

:

_server = new TestServer(new WebHostBuilder()
    .UseStartup<Startup>()
    .ConfigureTestServices(services =>
    {
        services.AddTransient<IFooService, MockService>();
    })
);
+12

Source: https://habr.com/ru/post/1675348/


All Articles