How to mock std::env::var_os?


There seem to be quite a few facilities for mocking out traits in Rust, however I’d like to unit test a function that makes use of var_os and I’m struggling to do so. As OsStr and OsString are private I can’t create a trait and then have an implementation that delegates to std::env that could in turn be mocked, and I can’t mock std::env directly as its a module rather than a trait/struct. Anyone have any suggestions for how best to test this function in an isolated way?



You can create OsStr/OsString from regular strings (there’s into and as_ref), so I’m not sure what’s the problem in wrapping it.

However, if you’re going to change the code, I’d go for something like struct Config that is trivial to set in tests, and eliminates direct use of env vars completely.



The problem with OsStr/OsString is I can’t define a function using them on the trait, as they are private, so var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> does not compile. by struct Config you mean reading the env vars elsewhere and then passing them in a struct?



They are definitely public types:



Oops, my bad, you’re right!