Search code examples
rustcommand-line-interfaceclap

How do I mock user input in the clap library for Rust?


I am currently building a Rust CLI with clap. Does anyone have any pointers as to how I can mock/mimic user input so I can write my tests?


Solution

  • Call Parser::try_parse_from() (or, if you are not using a derive(Parser), Command::try_get_matches_from()). These functions accepts an iterator of strings instead of consulting the process arguments, so you can pass in any strings you want to test with. It returns a Result, so that you can write tests for both success and parse errors.

    (This answer applies to clap version 4.0. Older versions have significantly different type and function names, but still have this capability.)