如何让Jargo忽略额外参数及任意数量的无用字符串?
Got it, let's sort out how to get Jargo to ignore those random "junk-be-here" style strings and any extra unrecognized arguments in your test. There are two main approaches depending on how much control you need:
1. Ignore All Extra/Unknown Arguments (Simplest Approach)
Jargo has a built-in method to skip any arguments that aren't defined in your argument setup. Just add .allowUnknownArguments() to your CommandLineParser configuration. This will automatically ignore all unrecognized strings, including your "junk-be-here" entries.
Here's your modified test code:
@Test public void testUsage() throws Exception { Argument<Integer> nrOfPotatoes = Arguments.integerArgument("-n").build(); ParsedArguments parsedArguments = CommandLineParser.withArguments(nrOfPotatoes) .allowUnknownArguments() // This line makes Jargo skip all unrecognized arguments .parse("-n", "123", "junk-be-here", "another-useless-string", "even-more-junk"); int potatoesToPlant = parsedArguments.get(nrOfPotatoes); System.out.println("Hold on, planting " + potatoesToPlant + " potatoes..."); }
This will work for any number of junk strings you throw at it—Jargo will just focus on the -n argument you defined.
2. Ignore Specific Junk Patterns (Granular Control)
If you only want to ignore certain strings (like those matching a "junk-" prefix, or exact "junk-be-here" entries) and still throw errors for other unrecognized arguments, use a custom unknownArgumentHandler:
@Test public void testUsage() throws Exception { Argument<Integer> nrOfPotatoes = Arguments.integerArgument("-n").build(); ParsedArguments parsedArguments = CommandLineParser.withArguments(nrOfPotatoes) .unknownArgumentHandler((argument, parser) -> { // Define your ignore rules here if (argument.equals("junk-be-here") || argument.startsWith("junk-")) { return UnknownArgumentAction.IGNORE; // Skip this junk string } // Throw an error for any other unrecognized argument return UnknownArgumentAction.THROW_EXCEPTION; }) .parse("-n", "123", "junk-be-here", "junk-another", "legitimate-unknown-arg"); // Note: "legitimate-unknown-arg" would trigger an exception here, while the junk strings are ignored int potatoesToPlant = parsedArguments.get(nrOfPotatoes); System.out.println("Hold on, planting " + potatoesToPlant + " potatoes..."); }
This gives you full control over which strings get ignored and which should be treated as invalid input.
内容的提问来源于stack exchange,提问作者jontejj

