Make Your Rust Code Unit Testable With Dependency Inversion

Use Traits to invert your Rust dependencies and keep your code loosely coupled and testable

Kraig McFadden
Rust in Production

--

Photo by James Peacock on Unsplash

It was an epiphany moment when I figured out Java classes could be mocked by extending them and overriding their public methods.

“Well, duh,” you’re probably thinking. Of course, you can do that, and that’s how half the mocking libraries work anyway! (Also, why not just use a mocking library?) But it was an epiphany moment for me. It’s like when you’re driving around town, and go down a street you haven’t been down before, but then it pops you out at a familiar intersection.

A new part of the map has been revealed in your mind. This was the same for me: it was a moment that tied together dependency injection, inheritance, and mocking for unit tests. I grasped what it meant to write testable code.

Since then, I’ve worked in Ruby and Rust and a few other languages. Ruby makes this whole process stupidly easy-it doesn’t care what you pass in as an argument or a dependency so long as you have methods with the same names. In Rust, however, this is much trickier. Rust is very picky about types, imports, and method signatures. It also does not have inheritance (unlike Java). So what are we supposed to do? Even if we inject…

--

--

Kraig McFadden
Rust in Production

Staff backend software engineer. Pursuing an MDIV at Reformed Theological Seminary. Princeton 2018 - Electrical Engineering. Opinions are my own.