Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 323
KamiWar Avatar asked Nov 26 '25 03:11

KamiWar


1 Answers

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.)

like image 61
Kevin Reid Avatar answered Nov 28 '25 00:11

Kevin Reid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!