How to mock std::env::var_os?

#1

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?

0 Likes

#2

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.

0 Likes

#3

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?

0 Likes

#4

They are definitely public types: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3469948368defbb1e1180450a5a55294

0 Likes

#5

Oops, my bad, you’re right!

0 Likes