How Unit Test is missing .NET ConfigurationSection

If I have code like this:

        public XALServiceConfiguration CreateInstance()
        {
            var config = ConfigurationManager.GetSection(ConfigurationSectionName) as XALServiceConfiguration;
            if (config == null)
                throw new ConfigurationErrorsException("Configuration element 'xalService' was not found or is not of correct type.");
            return config;
        }

      

How can I check if an exception is being thrown if the section is missing from the config file? For other tests, the config section must be in the config file, so I can't remove it from the file.

I am using Visual Studio 2008 Unit test environment.

+1


source to share


5 answers


I think the other answers so far have missed the point of your question, namely how to throw an exception.

With a static technique like this, you really have a hard time doing this - you will need to insert a specific configuration into your test. I seem to remember that .NET configuration management isn't particularly amenable to this, but I think it can be done. I don't have easy access to MSDN right now, but try to find a way to load the config instance instead of accessing it with just static methods. I may be wrong - there can be no way to do this.



Don't worry too much about 100% coverage - sometimes there are only conditions that cannot be verified, unfortunately :(

+2


source


You can run the test file in a separate application domain. For this you can specify the config file to use or even specify the config file as "bytes" (see AppDomainSetup Structure )



+2


source


To make Slace clearer, it would look like this:

try {
  XALServiceConfiguration config = CreateInstance();
} catch (ConfigurationErrorsException cee) {
  Assert.Fail("Could not create XALServiceConfiguration: " + e.Message);
}

      

This is not very good (since you are not explicitly testing for a null situation. If you want to go to this step, you may have to create your own config loader and then test it against a different configuration with a known missing partition.

+1


source


You can just catch the exception in status try catch

and do Assert

in catch.

0


source


0


source







All Articles