You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Jargo忽略额外参数及任意数量的无用字符串?

How to Make Jargo Ignore Junk Strings & Extra Arguments

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:16:34