c# - 集成测试 ASP.NET Core Web API 和 EF Core 时重新配置依赖项

标签 c# asp.net-core integration-testing entity-framework-core xunit2

我正在学习本教程
Integration Testing with Entity Framework Core and SQL Server

我的代码是这样的

集成测试类

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();
    }

据我了解,.UseStartUp 方法确保 TestServer 使用我的启动类

我遇到的问题是,当我的 Act 语句被命中时

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

我在启动类中收到连接字符串为空的错误。我想我对这个问题的理解是,当我的 Controller 从客户端被击中时,它会注入(inject)我的数据存储库,而数据存储库又会注入(inject)数据库上下文。

我认为我需要将服务配置为 new WebHostBuilder 部分的一部分,以便它使用在测试中创建的上下文。但我不确定该怎么做。

Startup.cs 中的 ConfigureServices 方法

        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>();
    }

最佳答案

@ilya-chumakov 的回答很棒。我只想再添加一个选项

<强>3。使用 WebHostBuilderExtensions 中的 ConfigureTestServices 方法。

方法 ConfigureTestServices 在 Microsoft.AspNetCore.TestHost 版本 2.1 中可用(在 2018 年 5 月 20 日是 RC1-final)。它让我们可以用模拟覆盖现有的注册。

代码:

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

关于c# - 集成测试 ASP.NET Core Web API 和 EF Core 时重新配置依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43543319/

相关文章:

asp.net-core - OpenCover 无法检测 .exe,因为无法加载 PDB/MDB

c# - 防止组合框在用户键入时更改所选选项。 C#

c# - 测试字符串是否可以转换为其他各种类型

c# - 使用 SQLConnection 连接到 SQL CE 数据库

c# - EF.Functions.Like 方法在升级到 .NET 6 后不起作用

web-config - 为什么我们需要 ASP .NET 5 wwwroot 中的 web.config?

java - mvn clean verify 集成测试失败 : No qualifying bean of type

integration-testing - 新的integration_test软件包仅显示 "Test starting..."[Android]

asp.net - 如何自动化功能/集成测试和数据库回滚

c# - 仅包含部分工作的 C#、MVC