[Removing duplication in tests] (Part 1) Move wiring of objects to class attributes

Recommended reading before you read this article: Mockito basics

Hot to get rid of duplicated code in tests

When we have multiple tests and all of them have similar givens we are tempted to extract those common givens to setup method or the field declarations. This might be a good idea when those givens are just wiring of dependencies. In most other cases it might be not a good idea.
Below I include an example for correct removing duplication of “givens” for multiple tests. Moving wiring of objects in field declarations. This way we do not test the wiring in the test, just the business functionality. The wiring should be tested in acceptance or end to end tests, not on unit level.

The example below also replaces string constants with variable names. For example in the tests we don’t care that the username is “john”. We only care that the username passed around is the same object. So we can move the definition of username out of the test to increase readability.

Please note that all fields are marked as final. This ensures that all wiring was done before we start testing the user object.

Before refactor

After refactor

I have not found any other scenarios for removing duplication in tests by moving common code into set up methods or class attributes. All other scenarios where duplication occurs pointed to problems in production code and design issues. Please take a look at all other parts for further details (coming soon).

Please comment! 🙂