Can I get Cargo to do link time mock/dependency substitution?


#1

In C++, I can set up a project to compile a separate test executable for each unit to test, and then use the linker to substitute mock implementations of dependencies. This allows me to write all classes as if I’ve never heard of mocks, and still cleanly replace dependencies with mock implementations at a later time. I’d like to do the same in rust.

In abstract, suppose I have modules foo and bar which provide structs Foo and Bar. struct Foo has a dependency on Bar. I want to create a mock implementation of the Bar struct and use it instead of the real Bar when testing foo, but I need to use the real Bar when testing bar.

I believe it’s reasonable to hope rust can do this in principle, but I’m having trouble seeing a way to get cargo to do it without forgoing cargo’s built in test, instead setting up a crate for each test executable and abusing file links to trick cargo’s file name & path expectations into pointing the crates at the files I want them to look at.


A mock injection strategy for rust
#2

rustc does not have a concept of library ABIs. The compiler sees a specific version of each dependency, and the runtime version must be exactly the same as the compile-time version as the compiler will freely do inlining and interprocedural analysis. So your best bet for this kind of “crate polymorphism” would be to use “path” in your dependency section, and probably some shenanigans to compile multiple versions of each tree…

I’m still not sure myself what Rust best practices for mocking are. Any takers?