12

I have the folowing tests:

[TestClass]
public class GeneralTest
{
    [TestMethod]
    public void VerifyAppDomainHasConfigurationSettings()
    {
        string value = ConfigurationManager.AppSettings["TestValue"];
        Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
    }

    [TestMethod]
    [HostType("Moles")]
    public void VerifyAppDomainHasConfigurationSettingsMoles()
    {
        string value = ConfigurationManager.AppSettings["TestValue"];
        Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
    }
}

The only difference between them is [HostType("Moles")]. But the first passes and the second fails. How can I read App.config from the second test?

Or may be I can add some another config file in other place?

Draco Ater
  • 20,820
  • 8
  • 62
  • 86
  • A great workaround was submitted to my similar question: http://stackoverflow.com/questions/9117248/cant-access-information-from-configuration-files-when-tests-have-host-type-mol – Nicholas Hill Feb 06 '12 at 12:05
  • I found this answer: http://stackoverflow.com/a/6151688/13390 to be the best way to change the config file when using moles. It works beautifully if you use custom configuration sections (actually, it's the only one that worked in that case). – Jorge Vargas Dec 14 '12 at 06:36

6 Answers6

17

Assuming you are trying to access values in appSettings, how about just adding the configuration at the beginning of your test. Something like:

ConfigurationManager.AppSettings["Key"] = "Value";

Then when your test tries to read the AppSettings "Key", "Value" will be returned.

Kipp
  • 711
  • 7
  • 10
  • 1
    Oh my. If it were up to me I would make this the accepted answer!!! Thank you so much. It's such a doh moment. lolz – pqsk Feb 17 '12 at 14:14
  • 4
    Just wanted to add to anyone interested adding a connection string is a little different: ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings("name", "connectionstring"); – pqsk Feb 17 '12 at 14:28
  • Worked a treat. Thanks, Kipp – Crwydryn Jul 25 '13 at 09:32
12

You just add your "App.Config" file to the unit test project . It will read automatically.

Shanthi Gopalan
  • 121
  • 1
  • 2
  • 3
    Sometimes the simplest solutions are the best - this works for me instead of all the faffing around with OpenExeConfiguration and the like... – noonand Feb 19 '13 at 11:28
6

See http://social.msdn.microsoft.com/Forums/en/pex/thread/9b4b9ec5-582c-41e8-8b9c-1bb9457ba3f6

In the mean time, as a work around, you could try adding the configuration settings to Microsoft.Moles.VsHost.x86.exe.config

  • 3
    According to the link, it's a bug and is being worked on. Just so ppl don't have to go over there and read the thread. – jcollum Dec 08 '10 at 16:52
  • This really sucks. We have some integration tests where (for better or worse) the testing app.config is actually quite large. I'm stuck reimplementing the ConfigurationManager/WebConfigurationManager. – BFree Aug 17 '11 at 15:08
5
    [ClassInitialize]
    public static void MyClassInitialize(TestContext testContext)
    {
        System.Configuration.Moles.MConfigurationManager.GetSectionString =
            (string configurationName) =>
                {
                    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                    Assembly assembly = Assembly.GetExecutingAssembly();
                    fileMap.ExeConfigFilename = assembly.Location + ".config";
                    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                    object section = config.GetSection(configurationName);
                    if (section is DefaultSection)
                    {
                        ConfigurationSection configurationSection = (ConfigurationSection) section;
                        Type sectionType = Type.GetType(configurationSection.SectionInformation.Type);
                        if (sectionType != null)
                        {
                            IConfigurationSectionHandler sectionHandler =
                                (IConfigurationSectionHandler)AppDomain.CurrentDomain.CreateInstanceAndUnwrap(sectionType.Assembly.FullName, sectionType.FullName);
                            section = 
                                sectionHandler.Create(
                                    configurationSection.SectionInformation.GetParentSection(), 
                                    null,
                                    XElement.Parse(configurationSection.SectionInformation.GetRawXml()).ToXmlNode());
                        }
                    }

                    return section;
                };
    }
  • 1
    Looks promising this mock of the ConfigurationManager, but if i use this to get an appSetting, the following error occurs: 'System.Configuration.ConfigurationErrorsException: The configuration section 'appSettings' has an unexpected declaration'. Any fix on this? – Dennis Dec 20 '11 at 16:12
  • @Dennis, to work-around that error, see the sample code here: http://social.msdn.microsoft.com/Forums/is/pex/thread/9b4b9ec5-582c-41e8-8b9c-1bb9457ba3f6 If you don't have any custom appSettings, you can just "return new NameValueCollection();" – Rami A. Jan 20 '14 at 07:53
2

I ran across this issue at work and didn't like any of these answers. I also have the problem that the configuration file is being read in a static constructor which means I can't Mole ConfigurationManager before the static constructor is executed.

I tried this on my home computer and found that the configuration file was being read correctly. It turns out I was using Pex 0.94.51006.1 at home. This is slightly older than the current one. I was able to find a download for the older academic version: http://research.microsoft.com/en-us/downloads/d2279651-851f-4d7a-bf05-16fd7eb26559/default.aspx

I installed this on my work computer and everything is working perfectly. At this point, I'm downgrading to the older version until a newer working version is released.

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
  • Welcome to Stack Overflow. This is a Q&A site, not a typical forum, so posting a question as part of your answer isn't going to get it proper attention nor is it appropriate for the site, since an answer to a question is supposed to only address that question. Normally I'd advise you to post your question separately, but asking whether a tool is still being developed is off-topic here. It's a question best addressed to the tool's developers. Thanks. – Adam Lear Dec 31 '11 at 01:53
0

This is what I am using to get the correct AppConfig and ConnectionString sections:

var config = System.Configuration.ConfigurationManager.OpenExeConfiguration(Reflection.Assembly.GetExecutingAssembly().Location);

typeof(Configuration.ConfigurationElementCollection).GetField("bReadOnly", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(System.Configuration.ConfigurationManager.ConnectionStrings, false);
foreach (Configuration.ConnectionStringSettings conn in config.ConnectionStrings.ConnectionStrings)
    System.Configuration.ConfigurationManager.ConnectionStrings.Add(conn);

foreach (Configuration.KeyValueConfigurationElement conf in config.AppSettings.Settings)
    System.Configuration.ConfigurationManager.AppSettings(conf.Key) = conf.Value;

Saw the ConnectionString part here

Community
  • 1
  • 1
donelodes
  • 15
  • 6