Home > Software design >  How to system / end-to-end test a NET5 class library
How to system / end-to-end test a NET5 class library

Time:09-29

I'd like to system test a class library I've written. I'm planning on creating a servicecollection extension method as described here:

    public static class IServiceCollectionExtension
{
    public static IServiceCollection AddExampleAzureLibrary(this IServiceCollection services)
    {
        services.AddScoped<IGetSecret, GetSecret>();
        services.AddScoped<IKeyVaultCache, KeyVaultCache>();
        services.AddScoped<IBlobStorageToken, BlobStorageToken>();
        services.AddScoped<IBlobWriter, BlobWriter>();
        return services;
    }
}

Which can then be called by my system test to configure the services, but how exactly to do that? At the moment I'm thinking the best way would be to create a console app to consume my library and test with that as described in this answer but is there a better way?

Edit: I have seen Microsoft's suggested approach which is to use a Test WebApplicationFactory, but as this isn't a web app, the approach is unsuitable.

CodePudding user response:

Inspired by this answer and this tutorial from Microsoft, I have solved this by doing the following:

  • Adding a service collection extension method as described in my question

  • Creating a hostbuilder in my test:

      [TestMethod]
      public void MyTest()
      {
          using var host = CreateHostBuilder().Build();
    
          using var serviceScope = host.Services.CreateScope();
          var provider = serviceScope.ServiceProvider;
    
          var className = new MyClass(provider.GetRequiredService<IMyRootInterfaceToBePassedIn>());
    
          myClass.CallSomeMethod();
      }
    
      private static IHostBuilder CreateHostBuilder() =>
          Host.CreateDefaultBuilder()
              .ConfigureServices((_, services) =>
                  services.AddMyServices());
    
  • Related