+++ date = '2024-12-29T13:42:30+01:00' draft = true title = 'Mocking in Rust with Dependency Injection' summary = "Learn more about me and why I am starting this blog." tags = ["rust", "testing"] +++ {{< lead >}} Rust is hard. Especially when trying to enforce object orientation as found in e.g. Java. {{< /lead >}} That is one of my takeways as a relatively new Rust developer from a recent endeavor during the winter break. With finally enough time to work on one of my currently most-used projects **picoKontroller** --- a multi-use MIDI controller software --- I dared to tackle one of this project's biggest shortcomings: Testing. {{< forgejo repo="ghoscht/picoKontroller" >}} Since the core functionality of this project depends on the presence of a MIDI device, as well as PulseAudio/Pipewire, I wanted to attempt to mock these subsystems in order to increase overall testability. In this context I decided to apply dependency injection with the goal to transform this system into a thoroughly testable and well structured project. ## Getting Started After some research on the most well known dependency injection and mockinng libraries for Rust I decided on [Shaku](https://github.com/AzureMarker/shaku) and [Mockall](https://github.com/asomers/mockall), being each the most renowned project in their respective category. {{< highlight rust "linenos=table" >}} #[derive(Parser)] #[command(version, about, long_about = None)] struct Cli { #[arg(long, help = "List all available MIDI devices.")] list_midi: bool, #[arg(long, help = "List all available MPRIS players.")] list_mpris: bool, } {{< / highlight >}} This was inspired by a [Japanese post on Qiita](https://qiita.com/no_job_swan/items/703f1f08f6a998aea183) by user _no\_job\_swan_, introducing [tauri](https://github.com/tauri-apps/tauri) --- an alternative to electron --- to developers coming from the JavaScript world who don't know Rust. ## First Approach tried to use traits as polymorphy -> upcast not possible don't use boxed traits [blog](https://bennett.dev/dont-use-boxed-trait-objects-for-struct-internals/) -> generics Shaku supports [generics](https://github.com/AzureMarker/shaku/blob/62ccac4f3704365bae71791ee43de6c5714078d4/shaku/tests/generic_modules.rs)