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.
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 🙁