Citrus Framework. Можно ли назначить переменную из ответа?

Я пытаюсь проверить следующие два вызова REST:

Запрос 1

GET getLatestVersion
Response: {"version": 10}

Запрос 2

POST getVersionData (body={"version": 10})
Response: {"version": 10, data: [...]}

Можно ли присвоить «версию» из запроса 1 переменной для использования в запросе 2 в рамках того же теста?

@CitrusTest(name = "SimpleIT.getVersionTest")
public void getVersionTest() { 
    // Request 1
    http()
            .client("restClient")
            .send()
            .get("/getLatestVersion")
            .accept("application/json");

    http()
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
            // Can the version be assigned to a variable here?
            .payload("{\"version\":10}");

    // Request 2
    http()
            .client("restClient")
            .send()
            .post("/getVersionData")
            // Idealy this would be a Citrus variable from the previous response
            .payload("{\"version\":10}")
            .accept("application/json");

    http()
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
            .payload("\"version\": 10, data: [...]");
}

person Andy Longwill    schedule 31.03.2017    source источник


Ответы (2)


Вы можете использовать выражения JsonPath:

http()
    .client("restClient")
    .receive()
    .response(HttpStatus.OK)
    .messageType(MessageType.JSON)
    .extractFromPayload("$.version", "apiVersion")
    .payload("{\"version\":\"@ignore@\"}");

Или вы можете использовать сопоставитель переменных create в полезной нагрузке:

http()
    .client("restClient")
    .receive()
    .response(HttpStatus.OK)
    .messageType(MessageType.JSON)
    .payload("{\"version\":\"@variable('apiVersion')@\"}");

Оба варианта создадут новую тестовую переменную apiVersion, на которую можно ссылаться с помощью ${apiVersion} в дальнейших тестовых действиях.

person Christoph Deppisch    schedule 31.03.2017
comment
Спасибо Кристоф! - person Andy Longwill; 31.03.2017

Один из подходов, который работает, состоит в том, чтобы извлечь значение из TestContext и назначить его как переменную.

@CitrusTest(name = "SimpleIT.getVersionTest")
@Test
public void getVersionTest(@CitrusResource TestContext context) {

    http(httpActionBuilder -> httpActionBuilder
        .client("restClient")
        .send()
        .get("/getLatestVersion")
        .name("request1")
        .accept("application/json")
    );

    http(httpActionBuilder -> httpActionBuilder
        .client("restClient")
        .receive()
        .response(HttpStatus.OK)
        .messageType(MessageType.JSON)
        .payload("{\"version\":\"@greaterThan(0)@\"}")
    );

    // This extracts the version and assigns it as a variable
    groovy(action -> action.script(new ClassPathResource("addVariable.groovy")));

    http(httpActionBuilder -> httpActionBuilder
            .client("restClient")
            .send()
            .post("/getVersionData")
            .payload("{\"version\":${versionId}}")
            .accept("application/json")
    );

    http(httpActionBuilder -> httpActionBuilder
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
    );
}

addVariable.groovy

Это извлекает переменную из ответа и добавляет ее в TestContext.

import com.consol.citrus.message.Message
import groovy.json.JsonSlurper

Message message = context.getMessageStore().getMessage("receive(restClient)");

def jsonSlurper = new JsonSlurper();
def payload = jsonSlurper.parseText((String) message.getPayload())

// Set the version as a variable in the TestContext
context.getVariables().put("versionId", payload.version)

Вопросы

  • Есть ли более аккуратный способ сделать это?
  • Есть ли способ назвать сообщения в MessageStore?
person Andy Longwill    schedule 31.03.2017