views:

363

answers:

4

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.

A: 

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

Slace
+1  A: 

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.

Travis
+1  A: 

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 :(

Jon Skeet
+1  A: 

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)

Christian.K
Nice. It's a pretty painful thing to do (and for a single test I'd probably not bother) but +1 for explaining how it *can* be done :)
Jon Skeet