Seemingly unending lines of code, thousands of files and commits, and numerous people and teams all contributing to the same codebase. For many, dealing with a largely untested Java codebase sounds about as fun as filing taxes. It’s not surprising, given how difficult it may be to understand how all the pieces work together. We have a few tips for how to get started:

Don’t start by refactoring

It’s likely that an extensive codebase hasn’t been touched in a while. Rewriting the code straight away might break existing behavior of the code that we want to maintain, or potentially introduce new bugs. The time to refactor is once you have covered enough cases with unit tests to have confidence that you can change the code without breaking something.

Split up the major areas of the code 

The end result of running your code should basically provide you with the user requirements. This will determine what your final product will need to be able to achieve, and in turn, allow you to categorize the different classes that need coverage. 

Different classes will also have different priorities, depending on, for example, the security risk involved, or the number of dependencies. By ensuring the core logic is covered, this will provide much more confidence in the code as a whole. 

Start in regions with the most flux

It can be daunting, and the only way to get through it is to start. If we agree that the purpose of unit testing is, among other things, to protect software from any unexpected changes, then the areas where the tests deliver the most benefit will be where the code is frequently changed. 

Before this, it’s likely that the code may need to be refactored into tidy, testable units, all while maintaining compatibility with any previous integration tests. The next step is to fix anything that is broken by refactoring. Any existing tests will also likely have to be updated, so that they can provide a backdrop for changes across the rest of the code. This process will have to be iterative.

Document

Prior to writing tests, outline exactly what they set out to achieve, and aim to write code based specifically on expected behavior. For the benefit of your co-workers or future-self, document the test setup, and any key requirements for each test case. When changes need to be made, or when a new developer is introduced, this will make life much easier.

Luckily for you, we also have a playlist of video tutorials to take you through Java unit testing, starting with the basics:

To see the code and instructions for each video in more detail, the Definitive Guide to Unit Testing is another useful resource. We’ve also put together a running list of tools and frameworks that make it easier to test Java code; find it here.