driis
driis

Reputation: 164291

How to Unit Test a 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 test that the exception is thrown if the section is missing from the configuration file ? For other tests, the configuration section needs to be in the config file, so I cannot actually remove it from the file.

I am using the Visual Studio 2008 Unit test framework.

Upvotes: 1

Views: 1407

Answers (5)

Ducati007
Ducati007

Reputation: 275

This is a good implementation for testing Config sections http://www.codeproject.com/Articles/71843/Unit-Testing-your-App-config-and-ConfigurationSect

Upvotes: 0

Christian.K
Christian.K

Reputation: 49260

You could run the testcase in a separate application domain. For such you can specify the configuration file to use, or even specify the configuration file as "bytes" (see AppDomainSetup Structure)

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500645

I think the other answers so far have missed the point of your question, which is how to provoke the exception.

Using a static technique like this, you really can't easily do it - you'd have to have a way of injecting the particular configuration into your test. I seem to remember that the .NET configuration management isn't particularly amenable to this, but I think it can be done. I don't have easy MSDN access right now, but try to find some way of loading an instance of a configuration instead of accessing it just with static methods. I may be wrong - there may be no way of doing it.

Don't worry too much about 100% coverage - sometimes there are just conditions which are infeasible to test, unfortunately :(

Upvotes: 2

tsimon
tsimon

Reputation: 8010

Just to make Slace's answer a bit more clear, it would look like this:

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

It's not great (as you are not explicitly testing the null situation. If you want to go to that step, you might have to create your own config loader and then test that against a different config with a known missing section.

Upvotes: 1

Aaron Powell
Aaron Powell

Reputation: 25099

You could just catch the exception in a try catch statment and do an Assert in the catch.

Upvotes: 0

Related Questions