Mocking ConfigurationManager.AppSettings

1,685 views
Skip to first unread message

Desmond Green

unread,
Dec 10, 2010, 4:50:38 AM12/10/10
to Rhino.Mocks
I am trying to write meaningful tests, using MSTest for the following
method:

public bool CheckDateFormat()
{
return
(String.Compare(ConfigurationManager.AppSettings[Constants.CultureToUse],
Constants.UK, true) == 0);
}

To do so, I want to check the expected path (with the value 'en-GB'
returned from app.config) as well as negative paths where the value is
different within the app.config file or where no value is present.

I do not want to have to dynamically add, remove or modify values
within the app.config file, but hoped that I could achieve my tests by
mocking ConfigurationManager. However, since the method is effectively
a 'black box' and encapsulates the use of ConfigurationManager, how
can I write MSTest code to do this?

Thank you.

Stephen Bohlen

unread,
Dec 22, 2010, 11:49:25 AM12/22/10
to rhinomocks
Use the Facade Pattern (http://www.dofactory.com/Patterns/PatternFacade.aspx) to wrap the ConfigurationManager in an interface that you can then mock and set proper expectations upon.

public interface IManageConfigSettings
{
    CultureConstant GetCulture();
}


public class MyAppsConfigManager : IManageConfigSettings
{
    public CultureConstant GetCulture()
    {
        return ConfigurationManager.AppSettings[Constants.CultureToUse];
    }
}

In your tests, inject a mocked IManageConfigSettings and set your expectation on it.

In general, you should do this anyway (Facade Pattern around annoying bits of the Framework) as an overall design strategy for your application so that you don't take a concrete dependency on the ConfigurationManager class in 100s of places throughout your code.  As an example, what would happen if you later decide to store current culture settings per user in a database somewhere?  You want to be able to update *only* the MyAppConfigManager class' GetCulture() method in one place rather than having to reach all over your application to change calls to ConfigurationManager.AppSettings[Constants.CultureToUse] everywhere :)

Best of luck,

Steve Bohlen
sbo...@gmail.com
http://blog.unhandled-exceptions.com
http://twitter.com/sbohlen



--
You received this message because you are subscribed to the Google Groups "Rhino.Mocks" group.
To post to this group, send email to rhino...@googlegroups.com.
To unsubscribe from this group, send email to rhinomocks+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rhinomocks?hl=en.


Reply all
Reply to author
Forward
0 new messages