1

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.

5 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)

1 Comment

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 :)
1

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.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.