homepage/content/posts/rust-di-mocking.md
GHOSCHT 1689a3126a
All checks were successful
Homepage deployment / deploy (push) Successful in 21s
Add first rough rust-di content
2024-12-30 19:11:26 +01:00

2.2 KiB

+++ 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 and 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 by user no_job_swan, introducing 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 -> generics

Shaku supports generics