我正在使用Citrus Java DSL测试REST服务。我想保存响应中的数据以进行高级操作。根据文档,我应该为此目的使用Citrus测试上下文。

我尝试用CitrusResource注解注入TestContext:

@CitrusResource
private TestRunner runner;

@CitrusResource
private TestContext context;


@When("^service sends request to get all orders$")
public void get_Orders() {
    runner.http(action -> action.client(httpClientName)
            .send()
            .get(basePath));
}

@Then("^Service gets response with preflight id: \"([^\"]*)\"$")
public void verify_Orders(String preflightId) {
        runner.http(action -> action.client(httpClientName)
            .receive()
            .response(HttpStatus.OK)
            .contentType("application/json;charset=UTF-8")
            .extractFromPayload("$[*].styleId", "ids")
            .validate("$[*].styleId", everyItem(not(isEmptyOrNullString())))
            .validate("$[*].styleId", hasItem(preflightId)));

    String ids = context.getVariable("${ids}", String.class);
}


但是出现了空指针异常

1 Scenarios (1 failed)
4 Steps (1 failed, 1 skipped, 2 passed)
0m5.541s

java.lang.NullPointerException


另外,我尝试在必需的方法中创建新的TestContext

@CitrusResource
private TestRunner runner;

@CitrusResource
private TestContext context;


@When("^service sends request to get all orders$")
public void get_Orders() {
    runner.http(action -> action.client(httpClientName)
            .send()
            .get(basePath));
}

@Then("^Service gets response with preflight id: \"([^\"]*)\"$")
public void verify_Orders(String preflightId) {
TestContext context = new TestContext();
        runner.http(action -> action.client(httpClientName)
            .receive()
            .response(HttpStatus.OK)
            .contentType("application/json;charset=UTF-8")
            .extractFromPayload("$[*].styleId", "ids")
            .validate("$[*].styleId", everyItem(not(isEmptyOrNullString())))
            .validate("$[*].styleId", hasItem(preflightId)));

    String ids = context.getVariable("${ids}", String.class);
}


并得到

com.consol.citrus.exceptions.CitrusRuntimeException: Unknown variable 'ids'

    at com.consol.citrus.context.TestContext.getVariableObject(TestContext.java:158)
    at com.consol.citrus.context.TestContext.getVariable(TestContext.java:133)
    at com.consol.citrus.context.TestContext.getVariable(TestContext.java:122)


你能帮我吗?

最佳答案

由于未知原因,注释@CitrusResource不会将TestContext实例注入该字段。您可以在下面使用替代方法。

首先,您需要创建并注入一个柑橘类实例。


  @CitrusFramework
  私人柑橘类柑橘;


然后:


  testContext = citrus.createTestContext();

10-08 13:34