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.
source to share
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 :(
source to share
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 )
source to share
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.
source to share
This is a good implementation for testing Config sections http://www.codeproject.com/Articles/71843/Unit-Testing-your-App-config-and-ConfigurationSect
source to share