Hangfire 无法构建集成测试

问题描述 投票:0回答:1

我是集成测试新手。我的 .Net 7 WebApi 使用 Hangfire,并且在调用 CustomWebApplicationFactory 时无法构建。我正在使用 xUnit 进行测试。

public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
    public Mock<IAnimals> animals { get; }

    public CustomWebApplicationFactory()
    {
        animals = new Mock<IAnimals>();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        base.ConfigureWebHost(builder);

        builder.ConfigureTestServices(services =>
        {
            services.AddSingleton(animals.Object);
            services.AddLogging(builder => builder.AddConsole().AddDebug());
        });
    }

}

我得到的错误是:

Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNetCore.TestHost.dll
An exception of type 'System.InvalidOperationException' occurred in 
Microsoft.AspNetCore.TestHost.dll but was not handled in user code
The server has not been started or no web application was configured.

我的日志记录语句 services.AddLogging() 将其输出为错误:

Exception thrown: 'System.InvalidOperationException' in Hangfire.PostgreSql.dll

在program.cs中我的hangfire配置是:

 var connectionString = builder.Configuration.GetConnectionString("PostgreSQLConnection");
 builder.Services.AddHangfire(config => config
   .UseSimpleAssemblyNameTypeSerializer()
     .UseRecommendedSerializerSettings()
     .UseStorage(new PostgreSqlStorage(connectionString)
 ));

如有任何帮助,我们将不胜感激!

我并不是真的打算测试 Hangfire 作业,但我确实需要测试其他服务。 有没有办法让hangfire构建(也许是内存数据库?)或者只是模拟hangfire或跳过它?

更新:

我尝试将 Hangfire 和 Entity 配置为内存数据库...有些东西仍然不太正确...

     builder.ConfigureServices(services => {
      // Configure Entity In-Memory database
      services.RemoveAll(typeof(AppDbContext));
      services.AddDbContext<AppDbContext>(opt => opt.UseInMemoryDatabase(databaseName: "IntegrationTestDb_" + DateTime.Now.ToFileTimeUtc()));

      services.RemoveAll(typeof(GlobalConfiguration));
      services.AddHangfire(config => config
         .UseSimpleAssemblyNameTypeSerializer()
         .UseRecommendedSerializerSettings()
         .UseMemoryStorage());
 });
c# integration-testing xunit hangfire .net-7.0
1个回答
0
投票

我最近遇到了同样的问题,最终得到了这个解决方案:

    var hangfireGiblets = collection
        .Where(s => s
            .ServiceType.FullName
            ?.Contains("hangfire", StringComparison.InvariantCultureIgnoreCase) == true)
        .ToArray();

    foreach (var hangfirePart in hangfireGiblets)
    {
        collection.Remove(hangfirePart);
    }

    collection.AddSingleton(Mock.Of<IGlobalConfiguration>())
        .AddSingleton(Mock.Of<JobStorage>())
        .AddSingleton(Mock.Of<IUpdateVendorDataJobsScheduler>())
        .AddSingleton(Mock.Of<RouteCollection>());
© www.soinside.com 2019 - 2024. All rights reserved.