使用Cucumber(和/或Citrus)执行异步步骤

时间:2017-08-29 15:00:46

标签: java cucumber cucumber-jvm cucumber-java citrus-framework

假设我有如下测试(使用黄瓜) -

Scenario: Login successfully to Facebook
  Given the user test exists
  And user name and password is entered
  When the login form is submitted
  Then I expose a HTTP-Rest service to validate the user name and password
  When I receive a validation success message
  Then display the welcome message to the user

这里,当调用"the login form is submitted"时,它会将请求提交给HTTP REST服务,该服务将使用{{1}将用户名和密码传递给另一个HTTP Rest服务(将由Citrus Framework公开)。这将验证数据并发送成功响应。因此"I expose a HTTP-Rest service to validate the user name and password""the login form is submitted""的步骤定义应该异步执行。

你能帮我吗 - 我怎么能用黄瓜(或/和柑橘)来实现这个目的。

注意:我没有使用任何"I expose a HTTP-Rest service to validate the user name and password应用程序来公开stub"的HTTP Rest服务;我试图使用"I expose a HTTP-Rest service to validate the user name and password框架公开服务。

步骤定义用java编写。

1 个答案:

答案 0 :(得分:2)

首先,您需要在项目中设置柑橘黄瓜扩展。然后你应该能够使用@CitrusResource注释,为你的步骤类注入一个测试运行器实例:

@CitrusResource
private TestRunner runner;

此外,您可以注入应该接收请求的http服务器实例。

@CitrusEndpoint(name = "userServer")
private HttpServer userServer;

然后,您可以使用测试运行器和服务器接收请求,并在步骤定义中发送响应:

@Then("^I expose a HTTP-Rest service to validate the user name and password$")
public void exposeHttpRestService() {
    runner.http(http -> http.server(userServer)
        .receive()
        .post()
        .payload("{\"username\": \"test\", \"password\": \"secret\"}"));

    runner.http(http -> http.server(userServer)
        .send()
        .response(HttpStatus.OK));
}

登录表单应使用单独的线程在单独的步骤定义中提交,以便创建异步性质:

@When("^the login form is submitted$")
public void submitForm() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        // do submit the form
    });    
}