Reputation: 77
The program takes an path to a configuration file. E.g. cargo run -- -c path/to/yaml
.
This does not however work with cargo test. cargo test -- -c path/to/yaml
and following error will occur: error: Unrecognized option: 'c'.
Clap provide a method fn from_args() -> Self
, but did not fully know how this would solve the problem. A similar problem was solved by making it a integration test and add
[[test]]
name = "cpp_test"
# path = "tests/cpp_test.rs" # This is automatic; you can use a different path if you really want to.
harness = false
to the cargo.toml file.
In my case I want to test some functions and thus unit test. I do not believe this would work.
Upvotes: 2
Views: 1817
Reputation: 13830
I think the simplest way is to have a fn main_body(args: Args)
that does the real work, and then just test main_body
by passing the args directly in your source code instead of on the command line.
use clap::Parser; // 3.1.18
#[derive(Parser)]
struct Args {
#[clap(short, long)]
name: String,
}
fn main_body(args: Args) -> Result<(), ()> {
// Your main body here
Ok(())
}
fn main() -> Result<(), ()> {
let args = Args::parse();
main_body(args)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test() {
let args = Args { name: "Bob".into() };
assert_eq!(main_body(args), Ok(()));
}
}
Upvotes: 1