Cannot Use ConfigurationManager inside Unit Test P

2019-02-16 09:01发布

问题:

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 aspx pages)

ProjectCore (all C# files - model)

ProjectTest (all tests)

in my ProjectCore, I am able to access the ConfigurationManager object from System.Configuration and pass information onto the project. However, when I ran a test where the ConfigurationManager is involved, I get the error

System.NullReferenceException: Object reference not set to an instance of an object.

Here is an example of the test

using System.Configuration;

[TestMethod]
public void TestDatabaseExists()
{
    //Error when I declare ConfigurationManager
    Assert.IsNotNull(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
}

in my other tests, ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString is what I set my data adapter's configuration string to, and returns a null error on the tests but not when I actually use the website. Any ideas?

回答1:

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.



回答2:

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.



回答3:

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);


回答4:

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