Cannot Use ConfigurationManager inside Unit Test Project

后端 未结 5 1767
孤独总比滥情好
孤独总比滥情好 2021-01-07 19:20

I\'m trying to write a unit test for my project, but it will not let me use the Configuration Manager. Right now my project is set up like

ASP.Net application (all a

相关标签:
5条回答
  • 2021-01-07 20:02

    It could be one of several issues:

    1. You didn't add app.config to your ProjectTest project.
    2. You didn't add connection string in your app.config.

    0 讨论(0)
  • 2021-01-07 20:06

    You are doing a unit test and in unit test your concentration should be the particular method trying to test and should remove extraneous dependencies. in this case, try mocking/moleing(use Microsoft Mole and Pex) system.configuration class; that will give a solution for sure.

    What I am saying, once you install MS moles-and-pex -> in your test project solution -> right-click the system assembly and choose create mole.

    That will give you a mole'ed version of configuration class which in turn will have a mocked version of configuration class -- using which you can bypass the problem you are facing.

    0 讨论(0)
  • 2021-01-07 20:07

    first of all you must make sure that you have an app.config file in your nunit tests project.

    To add it, you can open the project properties (right click on the project)

    Enter the details of your connection, it will generate a app.config file or add the right section within :

    In your Test class, add the reference to : System.Configuration; => using System.Configuration;

    For example you could use your connectionString by this way :

    [TestFixture]
    public class CommandesDALUnitTest
    {
    
        private string _connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    
        [Test]
        public void Method_Test()
        {
            string test = _connectionString;
                ....
        }
    }
    
    0 讨论(0)
  • 2021-01-07 20:16

    It is related to the /noisolation parameter in the command line of mstest.exe. Omitting the /noisolation parameter, it works.

    0 讨论(0)
  • 2021-01-07 20:22

    You also can use special configuration paths with the ExeConfigurationFileMap:

    // Get the machine.config file.
    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
    // You may want to map to your own exe.config file here.
    fileMap.ExeConfigFilename = @"C:\test\ConfigurationManager.exe.config";
    // You can add here LocalUserConfigFilename, MachineConfigFilename and RoamingUserConfigFilename, too
    System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
    
    0 讨论(0)
提交回复
热议问题