Among the many exciting features of the upcoming Spring ’15 release there is a hidden gem for developers coming: the new @testSetup annotation. This new annotation will let you refactor chunks of code common to each test within a test class in to a common setup method that is guaranteed to be called before each test method is run. When combined with a Factory pattern to actually do the creation of test data and settings, this becomes a powerful way to organize your code so that it is easy to read and understand, and consistent across projects.
Trying to remain DRY
Historically, unit tests have been a difficult place for developers to remain DRY. There are several solutions for this, but most get ignored or are underutilized due to the overriding need for unit tests to be exceptionally readable. Testing software is notoriously difficult, and anything that attempts this in an automated fashion needs to be simpler, more readable and more maintainable than the software it is testing – otherwise you may need to start testing the tests! Generally, the lack of patterns and desire to remain simple and readable leads to the opposite of what we would want in any other part of our code base: repeated code. It’s not uncommon to see code like the following, with repeated setup code at the beginning of each test method:
Oftentimes, developers will see this repeated code and attempt to remain dry by refactoring the code into a helper method which gets called at the beginning of each test:
While this mostly works, what we’d really like is for the framework to handle this for us so that we can avoid having to put in the extra method calls if possible.
@testSetup – removing repeated code
@testSetup is a new annotation that will allow you to specify methods that the test framework will run just before each test method runs. The test methods must return null and be static (similar to most other testing frameworks) but otherwise can do whatever is needed by your tests. This annotation is totally optional as well, so if you don’t need/don’t like it you don’t have to use it. Continuing our sample from above, we can refactor the code base to:
By being able to gloss over the setup details, the next person who has to maintain these tests can more easily focus on the core concept each method is trying to test hopefully promoting more reliable and robust code.
We are excited for this new annotation and will be exploring its creative uses when it’s released. As with any new release there are some important caveats to it, so we encourage you to read the documentation on it before attempting to refactor any existing code bases. If you are confused by this or want to know more, feel free to leave us a comment below or contact us!