How to Mock config file in .Net Core with xUnit

≡放荡痞女 提交于 2021-02-11 15:00:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!