A while ago Udi Dahan wrote that he’d like a way to configure objects by just setting property values on an object. those “setters” will be intercepted and saved to a some config object (or container) for the future use of the application.
Udi turned to me a while ago and asked if perhaps typemock could be used to do this. an unusual scenario for a mocking framework, but a valid one for an AOP framework (which typemock is sort of)
It lost my mind after a while but today I talked with udi again, and came up with a simple solution to his problem. Here is a simple class that can be used like this:
[Test]
public void HandleCallsOn_OnlyFirstInstanceGetsIntercepted()
{
List<object> args = new List<object>();
MyClass configure =
TypeHandler.HandlePropertyCallsOn<MyClass>(
delegate(Type type, string propertyName, object passedValue)
{
args.Add(passedValue);
});
configure.ConnectionString = “a”;
configure.SomeNumber = 3;
new MyClass().ConnectionString = “b”;
Assert.AreEqual(2,args.Count);
}
Calling “HandlePropertyCallsOn” and giving a callback allows you to do whatever you want when the properties are set (the real properties are never really set). The BIG plus is that the properties do not have to virtual for this to work.
here is the code of the class that does this. you can use this with the free Community Edition of Typemock Isolator by just adding a reference to it in your project.
Just copy this class into your project to use it.
public class TypeHandler
{
public static TFrom HandlePropertyCallsOn<TFrom>(Action<Type, string, object> callback)
{
MockObject<TFrom> mock = MockManager.MockObject<TFrom>(Constructor.NotMocked);
mock.MockMethodCalled+=delegate(object sender, MockMethodCallEventArgs e1)
{
callback(typeof(TFrom), e1.CalledMethodName, e1.SentArguments[0]);
};
foreach (PropertyInfo property in typeof(TFrom).GetProperties(BindingFlags.Public|BindingFlags.Instance))
{
mock.ExpectSetAlways(property.Name);
}
return mock.Object;
}
}
you can use this class to configure calls on even interfaces without having a real class on them, or on abstract classes and such.