CodeSandwich / Mocktopus

Mocking framework for Rust
MIT License
232 stars 20 forks source link

Mock `std` functions? #69

Closed AustinScola closed 2 years ago

AustinScola commented 2 years ago

Is it possible to mock standard library functions?

I tried doing something like this but it didn't seem to work:

#[test]
fn mock_current_dir() {
    env::current_dir.mock_safe(|| MockResult::Return(Ok(PathBuf::from("/foo/bar"))));

    let dir = env::current_dir().unwrap();
    assert_eq!(dir, PathBuf::from("/foo/bar"));
}
CodeSandwich commented 2 years ago

Hi @AustinScola! Unfortunately currently it's not possible to mock functions from std, because there's no way to annotate them with #[mockable]. There's some motion to enable custom stdlibs in Rust, at some point maybe it'd be possible with them.

AustinScola commented 2 years ago

Okay, thank you for your response. For the time being what I did was write a function which wrapped the std function I wanted to mock. Then I mocked my wrapper function. I think this is an okay workaround, but do you have a recommended other workaround (asking because I am new to Rust)? And if not feel free to close this issue.

CodeSandwich commented 2 years ago

I think that your workaround is the best, I can't think of anything better :slightly_smiling_face: