Unit Tests Best Practices – Should You Use Your Own Methods?

code-reuseprogramming practicesunit testing

Today I was watching a "JUnit basics" video and the author said that when testing a given method in your program, you shouldn't use other of your own methods in the process.

To be more specific, he was talking about testing some record-creation method that took a name and last name for arguments, and it used them to create records in a given table. But he claimed that in the process of testing this method, he shouldn't use his other DAO methods to query the database to check the final result (to check that record was indeed created with the right data). He claimed that for that, he should write additional JDBC code to query the database and check the result.

I think I understand the spirit of his claim: you don't want one method's test case to depend on the correctness of the other methods (in this case, the DAO method), and this is accomplished by writing (again) your own validation/supporting code (which should be more specific and focussed, hence, simpler code).

Nonetheless, voices inside my head started protesting with arguments like code duplication, unnecessary additional efforts, etc. I mean, if we run the whole test battery, and we test all our public methods thoroughly (including the DAO method in this case), shouldn't it be OK to just use some of those methods while testing other methods? If one of them is not doing what it's supposed to, then its own test case will fail, and we can fix it and run the test battery again. No need for code duplication (even if the duplicate code is somewhat simpler) or wasted efforts.

I have an strong feeling about this because of several recent ExcelVBA applications I've written (properly unit-tested thanks to Rubberduck for VBA), where applying this recommendation would mean a lot of additional extra work, with no perceived benefit.

Can you please share your insights about this?

Best Answer

The spirit of his claim is indeed correct. The point of unit tests is to isolate code, test it free of dependencies, so that any erroneous behavior can be quickly recognized where it is happening.

With that said, unit testing is a tool, and it is meant to serve your purposes, it is not an altar to be prayed to. Sometimes that means leaving dependencies in because they work reliably enough and you don't want to bother mocking them, sometimes that means some of your unit tests are actually pretty close if not actually integration tests.

Ultimately you're not getting graded on it, what's important is the end product of the software being tested, but you'll just have to be mindful of when you're bending the rules and deciding when the trade-offs are worth it.

Related Topic