I have written some code where I think I'm using an existing design pattern. My question - which one??
Scenario: I'm developing a project that will be pulling a lot of values out of the app.config file. I have elected to create a class which centralizes all of this request handling:
public class AppSettingsReaderCentral
{
AppSettingsReader _asr = new AppSettingsReader();
public string GetSomeStringValue()
{
string someValue;
try
{
someValue = (string)_asr.GetValue("SomeKeyValue", typeof(string));
}
catch { throw; }
return someValue;
}
public int GetSomeIntValue()
{
int someValue;
try
{
someValue = (int)_asr.GetValue("AnotherKeyValue", typeof(string));
}
catch { throw; }
return someValue;
}
// Lots of other methods - e.g., GetConnectionStr(), GetTableName(), GetMaxNumRetries(), etc...
}
I want to write unit tests for classes which invoke the methods on this class. Some of those tests are to make sure that any exceptions raised by these method calls are caught and handled correctly. (AppSettingsReader.GetValue(...) can throw either a ArgumentNullException or a InvalidOperationException.)
To use a mocking framework I would have had to create either an interface or abstract class for the AppSettingsReaderCentral class, identifying each method. Seemed like a lot of work. So, here's what I came up with:
First, an interface:
public interface IAppConfigReading
{
object GetValue(string key, Type type);
}
Next, a wrapper class:
public class AppSettingsReaderWrapper : IAppConfigReading
{
AppSettingsReader _realReader = new AppSettingsReader();
public object GetValue(string key, Type type)
{
try
{
return _realReader.GetValue(key, type);
}
catch { throw; }
}
}
I then modified my AppSettingsReader class, changing the private field to be of type IAppConfigReading, and adding a constructor:
public class AppSettingsReaderCentral
{
IAppConfigReading _asr; // ...changed type
AppSettingsReaderCentral(IAppConfigReading reader)
{
_asr = reader;
}
// Remaining code unchanged...
}
Within my unit tests, I can then create some fakes...
public class AlwaysThrowArgumentNullExceptionAppSettingsReader : IAppConfigReading
{
public object GetValue(string key, Type type)
{
throw new ArgumentNullException("unit testing");
}
}
An instance of this AlwaysThrow... class is then passed in as the constructor parameter to the AppSettingsReaderCentral instance used within my unit tests.
So, I've looked at definitions for Adapter, Bridge, Decorator, Facade, Intercepting Filter, Proxy, Template, and Visitor patterns. Bridge and Visitor patterns seem closest to describing what I'm doing. As I'm (obviously) not the most facile with design patterns, which one best describes what I'm doing? I'd like to give my AppSettingsReaderWrapper class a more appropriate name, such as AppSettingsReaderProxy, AppSettingsReaderBridge, etc.
Thanks!!!!
Aucun commentaire:
Enregistrer un commentaire