The problem with NUnit and app.config

前端 未结 9 770
孤独总比滥情好
孤独总比滥情好 2020-12-29 19:48

When i run a simple test on connection to DB check i receive an error in NUnit:

[Test]
public void TestConn()
{
    string  connectionString = Configuration         


        
相关标签:
9条回答
  • 2020-12-29 20:21

    Man give a look at: http://nunit.net/blogs/?p=9

    As him suggest I put a MyProjectTests.dll.config in project root and everything works.

    An example of my config file is:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
         <add key="TestKey" value="Ok!"/>
    </appSettings>
    </configuration>
    

    And I'm using the simple: ConfigurationManager.AppSettings["TestKey"];

    0 讨论(0)
  • 2020-12-29 20:22

    When a configuration file is used in the project in which a test is run, specific naming conventions must be followed.

    The configuration file name should be the name of the assembly file with the config extension. For example, the configuration file used to run MyUnitTest.tests.dll must be named MyUnitTest.tests.dll.config and it should be in the same directory as the MyUnitTest.nunit

    Also we can configure this in prebuilds like below

    copy $(SolutionDir)path-to-main-project\Web.config $(ProjectDir)App.config 
    
    0 讨论(0)
  • 2020-12-29 20:24

    See my answer nunit and configs You need to tell nunit what the name of the config file is. it looks for namespace.config by default it seams

    0 讨论(0)
  • 2020-12-29 20:32

    I was in the same situation and I tried to add app.config to NUnit project but the project couldn't identify it. The tricky workaround for me was to create a class library that contains an app config and turn in into my test project. At the end of the day, all NUnit and its adapter are NuGet packages that can be added for tests to a class library and tests work perfectly fine ran by Visual Studio and Resharper.

    And finally debugged my test and received the value from App.config file within my test project:

    0 讨论(0)
  • 2020-12-29 20:33

    Your unit tests should still work as long as you have the same configuration for your test project as for your main project.

    I'd suggest using a pre-build event in your test project to copy your application's configuration file over to the test project. This saves having to maintain two sets of configuration.

    copy $(SolutionDir)path-to-main-project\Web.config $(ProjectDir)App.config

    0 讨论(0)
  • 2020-12-29 20:34

    Yes, you can. You need to be sure that any configuration you are referencing in your tests actually exist in the app.config of the test project.

    In other words, the project where your test is in, does not have a connection string "FertigungRead" defined in its app.config.

    One way to do this is to add the app.config of the system under test to the test project as a link, this way any changes happen on both projects.

    0 讨论(0)
提交回复
热议问题