我正在尝试测试以下两个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: [...]");
}
答案 0 :(得分:2)
您可以使用JsonPath表达式:
http()
.client("restClient")
.receive()
.response(HttpStatus.OK)
.messageType(MessageType.JSON)
.extractFromPayload("$.version", "apiVersion")
.payload("{\"version\":\"@ignore@\"}");
或者您可以在有效负载中使用create variable matcher:
http()
.client("restClient")
.receive()
.response(HttpStatus.OK)
.messageType(MessageType.JSON)
.payload("{\"version\":\"@variable('apiVersion')@\"}");
这两个选项都会创建一个新的测试变量apiVersion
,您可以在进一步的测试操作中使用${apiVersion}
进行参考。
答案 1 :(得分:0)
一种有效的方法是从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)
问题