Search code examples
javacucumbercitrus-framework

How to inject TestContext using TestRunner and cucumber


I am testing REST services using Citrus Java DSL. I would like to save data from the response for advance operations. According to the documenation, I should use Citrus test context for this purposes.

I've tried to inject TestContext with CitrusResource annotation:

@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);
}

But got Null Pointer exception

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

java.lang.NullPointerException

Also, I've tried to create new TestContext in required method

@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);
}

And got

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)

Could you please help me with it ?


Solution

  • For unknown reason, the annotation @CitrusResource does not inject TestContext instance into the field. You can use a work-around below.

    First you need to create and inject a citrus instance.

    @CitrusFramework private Citrus citrus;

    And then:

    testContext = citrus.createTestContext();