Testing and mocking based on name conversion

A version that might actually fit Rust's design could be

mod color;

#[mock]
#[path = "color_mock.rs"]
mod color;

fn op() { … }

#[mock]
fn op() { … }

#[test]
fn test_op() { … }

with the semantics that an item tagged #[mock] is #[cfg(test)] and is allowed to shadow a non-#[mock] item.

However, Rust doesn't really want to encourage this kind of unconditional mocking for #[cfg(test)]. This just means that you're testing your mocks instead of the code you're actually going to be using at runtime. Instead, Rust much prefers you to write your code in a "sans IO" style, or make it generic over the service provider.

8 Likes