How To Read UnitTest Project's App.Config From Test With HostType("Moles")
Asked Answered
L

6

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?

Lightly answered 5/11, 2010 at 11:54 Comment(2)
A great workaround was submitted to my similar question: #9117748Exile
I found this answer: https://mcmap.net/q/165895/-change-default-app-config-at-runtime 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).Muggy
E
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

Earthwork answered 8/12, 2010 at 8:36 Comment(2)
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.Determinism
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.Sokoto
S
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.

Showman answered 31/12, 2011 at 6:27 Comment(2)
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. lolzGildus
Just wanted to add to anyone interested adding a connection string is a little different: ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings("name", "connectionstring");Gildus
C
12

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

Coconut answered 18/10, 2012 at 6:45 Comment(1)
Sometimes the simplest solutions are the best - this works for me instead of all the faffing around with OpenExeConfiguration and the like...Gormand
E
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

Earthwork answered 8/12, 2010 at 8:36 Comment(2)
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.Determinism
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.Sokoto
H
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;
                };
    }
Heteropterous answered 12/2, 2011 at 23:15 Comment(2)
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?Hogarth
@Dennis, to work-around that error, see the sample code here: social.msdn.microsoft.com/Forums/is/pex/thread/… If you don't have any custom appSettings, you can just "return new NameValueCollection();"Chloropicrin
T
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.

Twoway answered 31/12, 2011 at 1:39 Comment(1)
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.Romaine
T
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

Toliver answered 2/2, 2012 at 16:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.