我如何像 Cucumber Ruby 的 puts 那样在 Cucumber JVM 中捕获 STDOUT?

How do I capture STDOUT in Cucumber JVM like Cucumber Ruby's puts?

在 vanilla Cucumber 中,在步骤定义中调用 puts 的任何输出都被捕获为 "test output" 并相应地格式化,如以下输出示例所示:

Feature: A simple thing

  Scenario: A simple scenario # features/simple.feature:3
    Given I do a step         # features/steps/step.rb:1
      This text is output with puts

正如您在上面看到的,它在 "pretty" 输出格式中的缩进很有帮助。在 JSON 格式中,它甚至以结构化方式捕获:

    "keyword": "Scenario",
    "name": "A simple scenario",
    "line": 3,
    "description": "",
    "id": "a-simple-thing;a-simple-scenario",
    "type": "scenario",
    "steps": [
      {
        "keyword": "Given ",
        "name": "I do a step",
        "line": 4,
        "output": [
          "This text is output with puts"
        ],
      }
    ],

上面是用一个简单的特征文件和如下步骤定义生成的:

Given(/^I do a step$/) do
  puts 'This text is output with puts'
end

在 Java 中实现 Cucumber 步骤时是否有等效函数,我可以用它来以相同的方式捕获此输出?打印到 System.out 导致绕过捕获机制,很像在 Ruby.

中使用 STDOUT.puts

我还没有看到任何使用此功能的 Cucumber-JVM 示例,这与 Ruby Cucumber 的许多示例不同,但在 Cucumber 的 JSON 输出中显然有一个条目- "output," 的 JVM,因此我想一定有一种方法可以写入该字段。

看起来这可以通过写入表示当前 运行 场景的对象来完成。

public class StepDefs {
  private Scenario scenario;

  /* Need to capture the scenario object in the instance to access it
   * in the step definition methods. */
  @Before
  public void before(Scenario scenario) {
    this.scenario = scenario;
  }

  @Given("^I do a step$")
  public void iDoAStep() {
    scenario.write("This text is output with scenario.write");
  }
}

与 Ruby 中的 puts 调用一样,这会在 JSON 输出文件中捕获。它在 "pretty" 输出中也有颜色,尽管它不像 Ruby 实现那样缩进。尽管如此,这似乎是我能找到的最接近的等价物。