'Integration test with IOptions and KeyVault
I'm trying to write an integration test for an AD Service I have in my codebase, however the service I'm testing requires IOptions to be passed in to the constructor. To make matters worse we are using azure key vault for our config.
Here is my test so far:
[Fact]
public void Test_GetAccessToken_GetsAccessToken()
{
//Arrange
var azureAdOptions = Options.Create(new AzureAd());
var aadService = new MyPortal.Services.Implementations.AadService(azureAdOptions);
//Act
var accessToken = aadService.GetAccessToken();
//Assert
Assert.NotEmpty(accessToken);
}
This currently fails as the AzureAd object's properties are null.
my question is, how do I populate that object from Key Vault, given I'm in a test and all that stuff happens in the Startup.cs & Program.cs files*
This is my Program.cs file, where KeyVault is configured.
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context,config) =>
{
var settings = config.Build();
#if (!DEBUG)
var keyVaultName = settings["KeyVaultName"];
if (!string.IsNullOrEmpty(keyVaultName))
{
config.AddAzureKeyVault(keyVaultName);
}
#endif
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Solution 1:[1]
You could try to use a Web Application Factory if you're doing this as an integration test.
var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient();
var response = await client.SendAsync(SomeHttpRequestMessage);
This should load up your entire program including startup using the actual dependencies.
This nuget package is called mvc.testing and you can find some more information on it here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | scottdavidwalker |
