Tuesday, 26 July 2011

Fakes and mocks, and swapping between them

While working on some existing tests – they were building some chunky classes that I needed for some new tests -- it took me a while to spot that program to an interface applies just as much in tests as in real code, and that any objects used – and more particularly reused – in tests should be instantiated and configured in test setup, not in each test.

But then I thought – the whole way of doing testing brings this on us. To test, we need a) provide instances that implement interface a that the classes under test use, and b) provide instances whose behaviour we can modify and assert arbitrarily.

The second point means that it gets hard to combine different sorts of fake, mock and stub in shared non-trivial structures. As soon as you share, you’re typically constrained to using common interfaces in your shared structure – the same required by the classes under test.That immediately breaks all tests, because all tests need to know about some decorating test interface to modify and assert behaviour.

It seems that even if you have a Builder-like mechanism that fully configures instances of either fakes or mocks or whatever for you – you still need something to assert that the desired behaviour was seen.

No comments: