Can't read app.config in C# .NET Core unit test project with ConfigurationManager

前端 未结 10 807
迷失自我
迷失自我 2020-12-15 15:13

I\'ve created a simple unit test project to read an app.config file. Target framework is Core 2.0. I also created a Core 2.0 console app, to sanity-check myself to make sure

10条回答
  •  有刺的猬
    2020-12-15 16:13

    I came across the same issue with my xunit tests and solved it by using the instance of Configuration from ConfigurationManager. I put the static (normal) way it works in core, framework (but not unit tests) before I show the alternative way it works in all three:

            var appSettingValFromStatic = ConfigurationManager.AppSettings["mySetting"];
            var appSettingValFromInstance = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings.Settings["mySetting"].Value;
    

    And here is a similar/related issue. In case anyone needs to get a section you can do a similar thing, though the type must change in the app config:

    
        

    Code to grab section:

            var valFromStatic = ((NameValueCollection)ConfigurationManager.GetSection("customNameValueSectionHandlerSection"))["customKey"];
            var valFromInstance = ((AppSettingsSection)ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).GetSection("customAppSettingsSection")).Settings["customKey"].Value;
    

    I feel like I am also crazy, and I know there are newer ways of doing config in core, but if one wants to do something cross-platform this is the only way I know how. I'd be very interested if anyone has alternatives

提交回复
热议问题