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

前端 未结 10 831
迷失自我
迷失自我 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 15:59

    A hacky, but working way is to copy the config to the same folder as an entry assembly, whatever it is:

    [SetUpFixture]
    public class ConfigKludge
    {
        [OneTimeSetUp]
        public void Setup() =>
            File.Copy(
                Assembly.GetExecutingAssembly().Location + ".config",
                Assembly.GetEntryAssembly().Location + ".config",
                true);
    
        [OneTimeTearDown]
        public void Teardown() =>
            File.Delete(Assembly.GetEntryAssembly().Location + ".config");
    }
    

    Apart from adding this class, the only thing to make it work is to include app.config file in test project (without any copying options). It should be copied to the output folder as .dll.config at the build step, because it's kind of default logic.

    Note the documentation for OneTimeSetUpAttribute:

    Summary: Identifies a method that is called once to perform setup before any child tests are run.

    Although it should work for parallel test runs for a single project, there could be obvious troubles when running two test projects simultaneously, since the config would get overwritten.

    However, it is still suitable for containerized test runs, like in Travis.

提交回复
热议问题