问题
I want to mock the config file values in .NET Core.
I am using xUnit for unit test. I am using application insight.
I use config file for configuration. Now I want to mock that .cs config file in my unit test case.
var configurationPackage = statelessServiceContext.CodePackageActivationContext.GetConfigurationPackageObject("Config");
var appInsightsSection = configurationPackage.Settings.Sections["AppInsightsConfig"];
var appInsightsInstrumentationKey = appInsightsSection.Parameters["AppInsights_InstrumentationKey"].Value;
var configurationPackage
is coming null in testing.
So I want to mock this
statelessServiceContext.CodePackageActivationContext.GetConfigurationPackageObject("Config")
回答1:
You can do this by using the OSS/Nuget package 'ServiceFabric.Mocks'.
For an example, check this unit test.
Relevant code:
using static ServiceFabric.Mocks.MockConfigurationPackage;
[..]
//build ConfigurationSectionCollection
var configSections = new ConfigurationSectionCollection();
//Build ConfigurationSettings
var configSettings = CreateConfigurationSettings(configSections);
//add one ConfigurationSection
ConfigurationSection configSection = CreateConfigurationSection("AppInsightsConfig");
configSections.Add(configSection);
//add one Parameters entry
ConfigurationProperty parameter = CreateConfigurationSectionParameters("AppInsights_InstrumentationKey", "some value");
configSection.Parameters.Add(parameter);
//Build ConfigurationPackage
ConfigurationPackage configPackage = CreateConfigurationPackage(configSettings, nameof(configPackage.Path));
var context = new MockCodePackageActivationContext(
"fabric:/MockApp",
"MockAppType",
"Code",
"1.0.0.0",
Guid.NewGuid().ToString(),
@"C:\logDirectory",
@"C:\tempDirectory",
@"C:\workDirectory",
"ServiceManifestName",
"1.0.0.0")
{
ConfigurationPackage = configPackage
};
[..]
//pass the `MockCodePackageActivationContext` to the Service constructor.
来源:https://stackoverflow.com/questions/57785683/how-to-mock-config-file-in-net-core-with-xunit