
最好的实践是确保每个场景都是独立和可重复的。这意味着一个场景的执行不应该依赖于另一个场景的执行结果。然而,在某些特殊情况下,您可能需要在不同的场景之间共享数据。虽然不建议这样做,因为它可能会导致测试变得脆弱和难以维护,但本文将介绍一种实现方法,并提供更合适的替代方案。
利用全局变量传输数据 (不推荐)最直接的方法是使用全局变量。在你的Step中 在Definition类中,声明一个类的成员变量,并在Step场景中 在Definition中设置变量值,然后在另一个场景中设置Step 在Definition中使用。
public class MyFeatureClass {
private String folderUuid; // 全局变量
@When("^I create folder with \"([^\"]*)\" name api$")
public void createFolder(String name) {
// ... 你创建文件夹的逻辑 ...
response = RestAssured.given()
.baseUri(prp_url)
.accept("application/json")
.contentType("application/json")
.header("X-Auth-Token", xAuthToken.userAuth())
.header("Folder-Name", name)
.header("Folder-Uuid", "123456")
.queryParam("parentFolderUuid", "")
.when()
.post("/filesystem/createFolder")
.then().extract().response();
folderUuid = getJsonPath(response, "uuid");
}
@When("^I send create inside the folder with \"([^\"]*)\" name api$")
public void createInsideFolder(String name) {
// 使用全局变量 folderUuid
String parentFolderUuid = folderUuid;
response = RestAssured.given()
.baseUri(prp_url)
.accept("application/json")
.contentType("application/json")
.header("X-Auth-Token", xAuthToken.userAuth())
.header("Folder-Name", name)
.header("Folder-Uuid", "123456")
.queryParam("parentFolderUuid", parentFolderUuid)
.when()
.post("/filesystem/createFolder")
.then()
.extract().response();
}
}
警告: 这种方法有严重的问题。如果场景的执行顺序发生变化,或者某个场景跳过,folderuuid可能不会初始化,导致nulpointerexception或其他不可预测的行为。因此,强烈建议避免使用此方法。
使用 Background 关键字 (推荐)Background关键字提供了一种更优雅的方法来处理需要在多个场景中重复执行的步骤。Background定义中的步骤将在每个场景执行之前执行,类似于Junit或TestNG中的@Before注释。
在你的.在feature文件中,添加一个Background部分,并定义创建文件夹的步骤:
Feature: 测试 Background 功能
描述: 本功能旨在进行测试 Background 关键字
Background: 创建文件和文件夹
When I create folder with "XYZ" name api
Scenario: 创建子文件夹
Given Open my app
When I send create inside the folder with "1" name api
Then I can create files inside folder
为了在background中创建的文件夹UUID可以在后续场景中使用,您需要将folderUuid声明为全球变量,然后在createfolder方法中设置其值,就像前面的例子一样。
优点:
- 确保每个场景都以相同的初始状态开始。
- 避免场景之间的依赖关系。
- 提高了测试的可读性和可维护性。
虽然数据可以通过全局变量在Cucumber场景之间传输,但不建议这样做,因为它会使测试脆弱且难以维护。使用Background关键字是一个更合适的替代方案,它可以确保每个场景都以相同的初始状态开始,并避免场景之间的依赖。在设计Cucumber测试时,应始终优先考虑测试的独立性和可重复性。
以上是Cucumber中跨场景传输变量的详细内容:不推荐但可行的方案。请多关注图灵教育的其他相关文章!