Automaticaly Rollback Static Overrides When Testing Legacy Code

When working with legacy code, writing tests requires to exploit seams to -hack- inject custom behaviour. In his book Michael Feathers explains that singleton (the anti pattern) are often good starting seams. The idea is as follow :

  1. create a public method to override the singleton value
  2. make this method deprecated, obsolete or use a TEST_ONLY_ name prefix so that it is not called elsewhere in the code
  3. Call this method from your test code to inject a mock or whatever so that you can test in isolation

This works fine … until you end up with an unexpected failing test [long debugging session] that is in fact the result of a test not restoring a singleton it had overriden. You can try hard not to forget, or you can use some kind of auto restore test class. Here is how it could look like in C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using NUnit.Framework;

namespace Test.Utils
{
  public class CleanOverridesTest
  {
    private class StaticOverrider<T> : IDisposable
    {
      private readonly T _initialValue;
      private readonly Action<T> _setter;

      public StaticOverrider(T initialValue, Action<T> setter, T newValue)
      {
        _initialValue = initialValue;
        _setter = setter;

        _setter(newValue);
      }

      public void Dispose()
      {
        _setter(_initialValue);
      }
    }

    private List<IDisposable> _toDisposeAfterEachTest;
    private List<IDisposable> ToDisposeAfterEachTest
    {
      get
      {
        // NUnit enforces a single SetUp method, so we have to make sure the base SetUp method was called by subclasses
        Assert.IsTrue(BaseSetUpCalled, "Override SetUp and TearDown, and call base implementation.");
        return _toDisposeAfterEachTest;
      }
    }


    [SetUp]
    public virtual void SetUp()
    {
      _toDisposeAfterEachTest = new List<IDisposable>();
    }
    private bool BaseSetUpCalled
    {
      get { return _toDisposeAfterEachTest != null; }
    }

    [TearDown]
    public virtual void TearDown()
    {
      // Overides and restores should be done in reverse order
      ToDisposeAfterEachTest.Reverse();
      foreach(var disposable in ToDisposeAfterEachTest)
      {
        try
        {
          disposable.Dispose();
        }
        catch (Exception)
        { }

      }
      ToDisposeAfterEachTest.Clear();
    }

    protected void OverrideStatic<T>(T initialValue, Action<T> setter, T newValue)
    {
      ToDisposeAfterEachTest.Add(new StaticOverrider<T>(initialValue, setter, newValue));
    }
  }
}

Later in an actual test :

1
2
3
4
5
6
7
8
9
10
11
[TestFixture]
public class LegacyTest : CleanOverridesTest
{
  [Test]
  public void LegacyShouldWorkWhenZingAndZang()
  {
    OverrideStatic(BigManager.Instance, BigManager.TestOnlySetInstance, new BigInstanceMock());

    ...
  }
}

The singleton is automaticaly restored in the TearDown method of the base class. In C#, we are luky enough to have delegates so that we can pass the injection setter directly. In language without this feature, you could use reflection or anonymous class.

Of course, when the code is more reliably tested, you should try to move away from all this hack …

Comments