介绍测试GraphQL Java

宦翔
2023-12-01

I was recently asked by one of my friend how can we test the GraphQL APIs in Java. He is currently exploring Karate's capability, however, he doesn’t want to use Karate just for this as they’re already using TestNG based framework. And there is a graphql-java library which let’s you to implement GraphQL in Java and test, but using Spring Boot. My main goal is not to introduce Spring Boot just for the sake of testing the GraphQL API. I wanted to keep it simple!

目标是:

  • 不应带来各种依赖关系(此库当前仅依赖于杰克逊)。应该只将graphql文件转换为请求有效负载字符串。应该能够使用任何HTTP客户端库。应该能够使用任何Java测试框架。

这就是这个图书馆的诞生。 让我们直接跳一下如何使用它。

Getting Started

添加Maven依赖项:

<dependency>
    <groupId>com.vimalselvam</groupId>
    <artifactId>test-graphql-java</artifactId>
    <version>1.0.0</version>
</dependency>

我不使用摇篮,但是直接将此库添加为摇篮依赖性。

Let’s test the Pokemon GraphQ大号 API. We’re going to test the following query:

query pokemon {
  pokemon(name: "Pikachu") {
    name
  }
}

我们将触发此查询,并声明成功的响应代码和响应正文,名称密钥包含皮卡丘。

进行上述查询并将其放入宠物小精灵下src / test / resources / graphql /在您的Maven项目目录中。

我们可以使用以下两种方式之一在测试中加载该文件:

  • 使用输入流:
InputStream iStream = getClass().getResourceAsStream("/graphql/pokemon.graphql");
  • 使用文件:
File file = new File("src/test/resources/graphql/pokemon.graphql");

在本例中,我使用的是第二种方法文件。

读取文件后,只需将其传递给GraphqlTemplate类解析如下:

String graphqlPayload = GraphqlTemplate.parseGraphql(file, null);

第二个参数是变数用于参数化您的GraphQL查询。 我将在短时间内向您展示如何使用它,直到保留它为止空值。

而已! 现在,您有了graphql查询字符串,可以将其作为请求有效负载直接传递到首选HTTP客户端库上。

让我们来谈谈变数。 的GraphQL具有设置一些功能变数 and pass those 变数 at run time during execution of查询。 For that, we’ll modify our 宠物小精灵查询。

打开宠物小精灵文件并将其更改为:

query pokemon($name:String!) {
  pokemon(name: $name) {
    name
  }
}

这里$名称是变量,它仅接受串。 的!运算符表示这是必需变量。 让我们来看看如何处理变数我们的代码中的场景。

在将GraphQL查询转换为纯字符串之前,让我们创建变量:

ObjectNode variables = new ObjectMapper().createObjectNode();
variables.put("name", "Pikachu");

在这里我们正在使用com.fasterxml.jackson.databind.node.对象节点创建变量。 这个对象节点可以在我们的第二个参数中传递GraphqlTemplate类。

String graphqlPayload = GraphqlTemplate.parseGraphql(file, variables);

就是这么简单!

I’ve open sourced this library and can be found here: https://github.com/vimalrajselvam/test-graphql-java.

欢迎捐款。 如果您有任何想法或问题,请在上面的github链接中打开一个问题。

让我们看完整的示例代码:

package com.vimalselvam.graphql;

import java.io.*;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import org.testng.Assert;
import org.testng.annotations.Test;

import okhttp3.*;

public class TestClass {
    private static final OkHttpClient client = new OkHttpClient();
    private final String graphqlUri = "https://graphql-pokemon.now.sh/graphql";

    private Response prepareResponse(String graphqlPayload) throws IOException {
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), graphqlPayload);
        Request request = new Request.Builder().url(graphqlUri).post(body).build();
        return client.newCall(request).execute();
    }

    @Test
    public void testGraphqlWithInputStream() throws IOException {
        // Read a graphql file as an input stream
        InputStream iStream = TestClass.class.getResourceAsStream("/graphql/pokemon.graphql");

        // Create a variables to pass to the graphql query
        ObjectNode variables = new ObjectMapper().createObjectNode();
        variables.put("name", "Pikachu");

        // Now parse the graphql file to a request payload string
        String graphqlPayload = GraphqlTemplate.parseGraphql(iStream, variables);

        // Build and trigger the request
        Response response = prepareResponse(graphqlPayload);

        Assert.assertEquals(response.code(), 200, "Response Code Assertion");

        String jsonData = response.body().string();
        JsonNode jsonNode = new ObjectMapper().readTree(jsonData);
        Assert.assertEquals(jsonNode.get("data").get("pokemon").get("name").asText(), "Pikachu");
    }

    @Test
    public void testGraphqlWithFile() throws IOException {
        // Read a graphql file
        File file = new File("src/test/resources/graphql/pokemon.graphql");

        // Create a variables to pass to the graphql query
        ObjectNode variables = new ObjectMapper().createObjectNode();
        variables.put("name", "Pikachu");

        // Now parse the graphql file to a request payload string
        String graphqlPayload = GraphqlTemplate.parseGraphql(file, variables);

        // Build and trigger the request
        Response response = prepareResponse(graphqlPayload);

        Assert.assertEquals(response.code(), 200, "Response Code Assertion");

        String jsonData = response.body().string();
        JsonNode jsonNode = new ObjectMapper().readTree(jsonData);
        Assert.assertEquals(jsonNode.get("data").get("pokemon").get("name").asText(), "Pikachu");
    }

    @Test
    public void testGraphqlWithNoVariables() throws IOException {
        // Read a graphql file
        File file = new File("src/test/resources/graphql/pokemon-with-no-variable.graphql");

        // Now parse the graphql file to a request payload string
        String graphqlPayload = GraphqlTemplate.parseGraphql(file, null);

        // Build and trigger the request
        Response response = prepareResponse(graphqlPayload);

        Assert.assertEquals(response.code(), 200, "Response Code Assertion");

        String jsonData = response.body().string();
        JsonNode jsonNode = new ObjectMapper().readTree(jsonData);
        Assert.assertEquals(jsonNode.get("data").get("pokemon").get("name").asText(), "Pikachu");
    }
}

from: https://dev.to//email2vimalraj/introducing-test-graphql-java-4i7h

 类似资料: