ConfigurationManager.AppSettings Returns Null In Unit Test Project

前端 未结 4 432
故里飘歌
故里飘歌 2021-02-05 05:47

I have a C# unit test project with application settings in the app.config file. I am testing a class that exists in a different project. That class depends on bot

4条回答
  •  野性不改
    2021-02-05 06:25

    If you're using .NET Core your problem could be a known issue caused by the fact that the test process runs as testhost.dll (or testhost.x86.dll), which means the runtime config file is expected to be named "testhost.dll.config" (or "testhost.x86.dll.config"), instead of the app.config output (ex: "MyLibrary.Tests.dll.config").

    To fix it, add the code below to your project file (.csproj, etc) inside of root node . During build, two copies of app.config will be put in the output directory and named "testhost.dll.config" and "testhost.x86.dll.config", which will get your app settings working again. (You only need 1 of these files but it's safer to include both.)

    
      
      
    
    

    I recommend app.config only as a temporary solution. If you're like me you might have run into the problem while upgrading a .NET Framework project to .NET Core and needed a quick fix. But don't forget to look into the new, more elegant solutions provided by .NET Core for storing app settings.

提交回复
热议问题