Why Tests Aren’t Written Inline with the Code They Test

bddliterate-programmingtestingunit testing

I've been reading a bit about Literate Programming recently, and it got me thinking… Well-written tests, especially BDD-style specs can do a better job at explaining what code does than prose does, and have the big advantage of verifying their own accuracy.

I've never seen tests written inline with the code that they test. Is this just because languages don't tend to make it simple to separate application and test code when written in the same source file (and nobody's made it easy), or is there a more principled reason that people separate test code from application code?

Best Answer

The only advantage I can think of for inline tests would be reducing the number of files to be written. With modern IDEs this really isn't that big a deal.

There are, however, a number of obvious drawbacks to inline testing:

  • It violates separation of concerns. This may be debatable, but to me testing functionality is a different responsibility than implementing it.
  • You'd either have to introduce new language features to distinguish between tests/implementation, or you'd risk blurring the line between the two.
  • Larger source files are harder to work with: harder to read, harder to understand, you're more likely to have to deal with source control conflicts.
  • I think it would make it harder to put your "tester" hat on, so to speak. If you're looking at the implementation details, you'll be more tempted to skip implementing certain tests.