在 picocli 中,我们可以以声明方式和编程方式注册子命令。 它是双向的,但根据文档的单元测试对于编程版本失败了。
这是单元测试:
@Test
void testApp() {
App app = new App();
CommandLine commandLine = new CommandLine(app);
int code = commandLine.execute("sub1", "param1");
assertEquals(0, code);
}
声明式变体 1 ✅
@CommandLine.Command(name = "foo", subcommands = { App.Sub.class })
public class App {
public static void main( String[] args )
{
CommandLine commandLine = new CommandLine(new App());
System.exit(commandLine.execute(args));
}
@CommandLine.Command(name = "sub1", description = "sub1")
public static class Sub implements Runnable {
@CommandLine.Parameters
public String [] params;
@Override
public void run() {
System.out.println("Sub " + params[0]);
}
}
}
以编程方式实现变体 2 ❌
@CommandLine.Command(name = "foo")
public class App {
public static void main( String[] args )
{
CommandLine commandLine = new CommandLine(new App())
.subCommand("sub1", new App.Sub());
System.exit(commandLine.execute(args));
}
@CommandLine.Command(name = "sub1", description = "sub1")
public static class Sub implements Runnable {
@CommandLine.Parameters
public String [] params;
@Override
public void run() {
System.out.println("Sub " + params[0]);
}
}
}
这非常令人困惑,我花了几个小时来检测也许不是我的应用程序代码丢失了某些东西...... 我假设我需要以编程方式,那么这个变体的单元测试应该是什么样子?
亲切的问候 多米尼克
不要调用
subcommand
方法,而是调用 addSubcommand
方法以编程方式注册子命令。
请参阅手册中的以编程方式注册子命令部分:
CommandLine commandLine = new CommandLine(new Git())
.addSubcommand("status", new GitStatus())
.addSubcommand("commit", new GitCommit())
.addSubcommand("add", new GitAdd())
.addSubcommand("branch", new GitBranch());
…