运行 RestAssured smoke tests with maven on different environments with its own unique API keys 作为headers

Running RestAssured smoke tests with maven on different environments with its own unique API keys as headers

我有一组标记为冒烟测试的 RestAssured 测试,我正在使用 Maven 运行 通过命令行使用命令对它们进行 运行 mvn 测试 -PSmokeTests -Denv=QA

env=QA 在 pom.xml 中定义为系统 属性。我明白,如果我需要 运行 在不同的环境(如 dev 或 staging 或 prod)上执行此操作,我可以将其指定为命令行参数,并且在我的测试中,我可以处理它。

然而,这些环境中的每一个都需要使用不同的 API 密钥,用于在 API 请求中作为 header 传递的环境。我将密钥存储在单独的 headers_key 文件中并在代码中引用它们。但是我想避免这种情况,因为当我将代码推送到 git 这样的源代码存储库时,我不希望密钥可见。

在 maven 中有什么有效的方法来处理这个问题吗? API 密钥的存储方式是否可以根据环境选择它们,而不必将它们存储在 RestAssured 框架内的单独文件中?

这是我的 pom.xml 片段:

    <profile>
        <id>SmokeTests</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.19.1</version>
                    <configuration>
                        <systemPropertyVariables>
                            <env>${env}</env>
                        </systemPropertyVariables>
                        <suiteXmlFiles>
                            <suiteXmlFile>SmokeTests.xml</suiteXmlFile>
                        </suiteXmlFiles>
                    </configuration>
                </plugin>
            </plugins>
        </build>
        </profile>

这就是我目前在 RestAssured 代码中处理它的方式:

public static RequestSpecification getJSONRequestSpecification() {
    REQUESTBUILDER = new RequestSpecBuilder();
    env = System.getProperty("env");
    if (env.matches("QA")) {
        REQUESTBUILDER.setBaseUri(Path.BASE_URI_QA);
        REQUESTBUILDER.addHeader("X-Api-Key", APIKeys.QA_API_KEY);
    } 
    if (env.matches("Dev")) {
        REQUESTBUILDER.setBaseUri(Path.BASE_URI_Dev);
        REQUESTBUILDER.addHeader("X-Api-Key", APIKeys.Dev_API_KEY);
    } 
    if (env.matches("Staging")) {
        REQUESTBUILDER.setBaseUri(Path.BASE_URI_Staging);
        REQUESTBUILDER.addHeader("X-Api-Key", APIKeys.Staging_API_KEY);
    } 
    if (env.matches("Integration")) {
        REQUESTBUILDER.setBaseUri(Path.BASE_URI_Int);
        REQUESTBUILDER.addHeader("X-Api-Key", APIKeys.Int_API_KEY);
    } 
    REQUESTBUILDER.setContentType(Headers.CONTENT_TYPE_JSON);
    REQUEST_SPEC = REQUESTBUILDER.build();
    REQUEST_SPEC.log().ifValidationFails();
    return REQUEST_SPEC;
    }

您可以使用类似于传递 env 的命令行变量来传递 api 键。

mvn test -PSmokeTests -Denv=QA -DapiKey="keyvalue123"

您可以使用以下命令在 java 项目中访问 api 密钥

String apiKey = System.getProperty("apiKey");