It seems to be common pratice to separate the unit test code from the classes under test. In Ruby for example, the convention is to have a test/test_my_class.rb file which contains the test code for class MyClass (itself stored in lib/my_class.rb). But is it actually good pratice to move the test code out into another file?
What we have already learned in the past is that inline documentation – i.e. keeping the documentation next to the code – is in many cases superior to external documentation, for the following reasons:
- It lowers the barriers to write documentation at all.
- It is more likely that the documentation stays up-to-date (in sync with the code).
- It eases the understanding of the code.
Unit tests are not so different. They too document behaviour, just in a different language, one that is machine readable and executable. Having the unit tests within the same class (and file) could lead to some interesting advantages:
- It lowers the barriers to write unit-tests at all.
- It is more likely that the unit-tests stay up-to-date when new functionality is added.
- It eases the understanding of the code as the unit-tests can serve as additional documentation.
You mostly see the same advantages as for inline documentation. This is because unit tests exhibit exactly the same problems as documentation: Developers don’t like to write or keep them up-to-date. With inline unit testing this situation could be improved.