spring-bootspring-graphql

Java 21 Spring Boot 3.3.1 How to get GraphQlTester to use main/resources/graphql-documents/


I have a Java 21 Spring Boot 3.3.1 application. I have several GraphQL APIs, and I also need to send several GraphQL requests to other services. I also have GraphQlTester tests. However, I have several GraphQL template files in my main/resources/graphql-documents/ directory that I can use for my GraphQL tests. However, the GraphQlTester looks for the documents under the test/resources/graphql/ directory. I don't want to have duplicate files, especially since I have a quite a few templates. Can GraphQlTester be configured to look at the main/resources/graphql-documents/ directory so I do not need to have a ton of duplicate files?

Here is a sample of how I am using the GraphQlTester:

        graphQlTester.documentName(GQL_MY_QERY)
                .variable(ID, "myId")
                .execute()
                .path(GQL_MY_QERY)
                .entity(MyResult.class)
                .satisfies(actualResult -> assertEquals(expectedResult, actualResult));

It works just fine if I put the documents in the test directory. I just don't want tons of duplicate files if I don't need to.


Solution

  • Assuming that you already have a configured GraphQlTester instance, you can mutate it the following way:

    List<Resource> resources = List.of(new ClassPathResource("graphql-documents"), new ClassPathResource("graphql"));
    ResourceDocumentSource documentSource = new ResourceDocumentSource(resources, ResourceDocumentSource.FILE_EXTENSIONS);
    graphQlTester = graphQlTester.mutate().documentSource(documentSource).build();