I am writing integration tests for my app which uses .net5 I have used WebApplicationFactory with IHostBuilder for setting up environment.
Custom fixture ->
public class TestFixture<T> : WebApplicationFactory<Program>
{
protected override IHostBuilder CreateHostBuilder()
{
var builder = Host.CreateDefaultBuilder();
builder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.SetBasePath(env.ContentRootPath);
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
config.AddEnvironmentVariables();
})
.ConfigureServices((hostContext, services) => { services.Configure(hostContext); });
return builder;
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureTestServices((services) =>
{
services.RemoveAll(typeof(IHostedService));
});
}
}
services.Configure(hostContext) calls UnityContainer which registers workflows(https://github.com/danielgerlag/workflow-core).
Test class(gives error when test is run)-> Error
Error desc -> No application configured. Please specify an application via IWebHostBuilder.UseStartup, IWebHostBuilder.Configure, or specifying the startup assembly via StartupAssemblyKey in the web host configuration
Add this code : .ConfigureWebHostDefaults(b => b.Configure(app => {}));
after .ConfigureServices call
you are using a Worker Service that doesn't run a web host. However, the WebApplicationFactory still expects one, So create an empty web application.
@Vaibhav's answer above was very helpful but still not super obvious on how to apply if working directly with WebApplicationFactory in .Net6+ using minimal hosting. Hopefully this is helpful to someone else...
using WebApplicationFactory<Program> webApplicationFactory =
new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.Configure(_ => { });
});
Without that empty configure, you will get the following error and it was driving me mad!
System.InvalidOperationException: 'No application configured.
Please specify an application via IWebHostBuilder.UseStartup,
IWebHostBuilder.Configure, or specifying the startup assembly
via StartupAssemblyKey in the web host configuration.'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With