When I'm writing tests in a specific code base, I often need set a static property before my newly added code, and re-set it back when leaving. Example
public void SomeMethod(){
val oldVal = Notifier.DoNotify;
Notifier.DoNotify = false;
// Some code...
Notifier.DoNotify = oldVal;
}
I think this way is ugly and I want something nicer and which also makes it harder forget to re-set the value.
I tried cooking something up and got this. I see some benefits, but it's a pretty talky solution.
public class ValueHolder<T> : IDisposable
{
private readonly Action<T> setter;
private readonly T oldVal;
public ValueHolder(Func<T> getter, T tempVal, Action<T> setter)
{
this.setter = setter;
oldVal = getter();
setter(tempVal);
}
public void Dispose()
{
setter(oldVal);
}
}
Which then is used like
public void SomeMethod(){
using(new ValueHolder<bool>(() => Notifier.DoNotify, false, (b) => Notifier.DoNotify(b)) {
// Do something ...
}
}
What is a good solution to this?
(Edit removed reference to testing. Seemed to distract from what I wanted to ask)