DEV Community

Discussion on: Writing 'Testable' Code Feels Wrong

Collapse
 
bitschupser profile image
Alex Rampp

Hi Jon,

thank you for sharing this thought. Personally, I'm a big advocate of developing test first since it helps me getting clear about the expectations I have to the unit I'm working on. As I mentioned the term 'unit', unit-testing denotes the activity on verifying that this unit does the right thing.

In my opinion, one very interesting question on unit testing is: what is 'a unit'? Is it a function, a class, a module (whatever that is in you architecture and/or technology), or sometimes a whole (micro-)service? I think there is no general answer - it highly depends on the technology, on the architecture and on the environment you're working in.

When it feels wrong adding additional abstractions just for the sake of test-ability, then perhaps the 'unit' was chosen to be too fine grained. I had an interesting discussion on GitHub a few years ago where I refactored a parser module to make it more testable for the price of making it more complicated. At the end, the original author convinced my seeing the parser as a black box and just test that a given input produces the correct data structure. In this example, I had a wrong definition of 'the unit'.

But sometimes there are also cases where test lead to a missing abstraction. Dependencies to external systems, legacy components or network calls are good candidates for this. While coding, it's easy to just open a network socket and write some data to it. But it's a good idea to abstract these details in some small, low-level components. Sometimes tests lead to such refactorings, since code depending on a network socket is very hard to test. This is the core idea of Test Driven Design.