System.InvalidOperationException : No method public static IHostBuilder CreateHostBuilder
Issue Description:
.NET Core Integration Testing runtime gives below error,
System.InvalidOperationException : No method ‘public static IHostBuilder CreateHostBuilder(string[] args)’ or ‘public static IWebHostBuilder CreateWebHostBuilder(string[] args)’ found on ‘BooksApi.Program’. Alternatively, WebApplicationFactory`1 can be extended and ‘CreateHostBuilder’ or ‘CreateWebHostBuilder’ can be overridden to provide your own instance.
Resolution
The issue I found to be due to recent improvements and updates to the .NET Core version 3.0.
To fix the issue here one needs to override CreateHostBuilder and provides custom implementation as shown below.
Please note that the .NET Core 3.0 + preview version is still evolving. You might get a few issues while migrating from .NET Core 2.2 to .NET Core 3.0 or 3.1.
Using .NET Core 3.1
Alternatively one can create Software under test i.e Target service using .NET Core 3.1. I found you don’t need to override CreateHostBuilder.
This seems as per the design update in the .NET Core 3.1 version. The target service host internally uses Generic Host Builder using CreateDefaultBuilder
One can use WebApplicationFactory directly or custom fixture class AppTestFixture explained in this article in detail.
With this, you get a choice to use default host builder of target service or override it within AppTestFixture if needed addressing in Test needs.
Below should works for you,
public class AppTestFixture : WebApplicationFactory<Startup>
{
//override methods here as needed
}
If by any means you need to override the method, please use below way to do the same.
public class AppTestFixture : WebApplicationFactory<Startup>
{
//override methods here as needed
protected override IHostBuilder CreateHostBuilder()
{
return Host.CreateDefaultBuilder().ConfigureWebHostDefaults(builder =>
builder.UseStartup<Startup>());
}
}
The above mechanism can also be used if you have a TestStartup class derived from the Startup class.
For more details on the changes, please check below article,
- Integration Testing in ASP.NET Core series with an example
- Generic Host Builder in ASP.NET Core – CreateDefaultBuilder
That’s All !!
Did the above steps resolve your issue?
Please sound off in your comments below!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.