Our article on dependency injection carried a sample unit test for seven months. It could not pass. It read a value before the code had produced one and compared the result with a name. Nobody noticed, because nobody ran it. That is the argument for this month's rewrite, and for checking sample code the way you check production code.
What the Technique Is For
Dependency injection means a component is handed what it needs and does not build it. The business case is replaceability: a test can hand it a fake payment service, and a release can hand it the real one. On Android the standard tool is Hilt, which Google describes plainly: "Hilt is Jetpack's recommended library for dependency injection in Android" (Android).
The Part Most Teams Overbuild
The surprise in the official testing guide is its first rule: "Hilt isn't necessary for unit tests, since when testing a class that uses constructor injection, you don't need to use Hilt to instantiate that class" (Android). The framework is for assembling the app. A test assembles one object by hand.
Teams that route every test through the framework pay for it in build time. The same guide warns that one of its replacement mechanisms "can significantly impact unit test build times". Slow tests get run less, and tests that are not run are where a sample like ours survives.
The Default That Wastes Memory
A second correction concerned how long objects live. The framework's default is the frugal one: "By default, all bindings in Hilt are unscoped. This means that each time your app requests the binding, Hilt creates a new instance of the needed type." Marking everything as a long-lived singleton, a common habit, keeps objects alive for the whole session that one screen needed for a minute.
What to Ask Your Team
- How long does our unit test suite take, and why? If the injection framework is in every test, that is part of the answer.
- Which objects live for the whole session? Each one should have a reason.
- Do we run the code samples in our own documentation? We did not, and it showed.
-Rocky
#SoftwareQuality #TestStrategy #MobileEngineering #EngineeringDreams #StrategiaX
Originally published on ANDROID-ARCHITECT, the Android engineering blog of Strategia-X, with the setup, the modules and the corrected test.
