'Is it possible to override std::env::Args in Rust?
I am writing a few test cases in my rust application. I want to set values of set::env::Args, is that allowed in rust ?
"In golang, we can directly assign values to os.Args"
If possible, then what method can I use to do so ?
Solution 1:[1]
As you can see in the documentation, an Args struct is an Iterator that yields Strings. Thus if you make the functions you want to easily pass custom arguments to accept an Iterator<Item=String> parameter, then you can test them easily as well:
fn use_args(args: impl Iterator<Item=String>) -> usize {
args.map(|arg| arg.len()).sum()
}
fn main() {
println!("{:?}", std::env::args());
println!("{}", use_args(std::env::args()));
}
#[test]
fn test_use_args() {
assert_eq!(use_args(std::iter::once("123".to_string())), 3);
assert_eq!(use_args(std::iter::once("target/debug/playground".to_string())), 6+1+5+1+10);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hkBst |
