DEV Community

Cover image for Testing your GraphQL APIs in a Spring-boot app

Posted on • Originally published at Medium

Testing your GraphQL APIs in a Spring-boot app

This article is the fourth article of the series GraphQL, from theory to real-world with Spring-boot. But don’t worry, The stories are designed to be consumed independently from the other stories. You just have to grab the current state of the project by doing this:

git clone -n && cd springboot-graphql-error-handling

git checkout 71d5f771bf9a6feaf8a5b7f62947442aace2b127
git switch -c my_experimental_branch

In this article, we will see how we can test the resources that we have defined in the project.

You can check out the corresponding video here:

We want to make sure the tests are fast, reliable and easy to understand.

If you have not cloned our project, then you may need these dependencies in your pom.xml


We have three resources to test, we will then define three GraphQL queries to load from our resources folder.

If it’s not already done, create this directory in your project:

src/test/resources/graphql then create these 3 request file in it.

    createUser(username: "johndoe",password: "mypassword"){
    deleteUser(username: "johndoe"){
    getUser(username: "johndoe",password: "mypassword"){

In our test package we will create 2 classes :
One for testing mutations and another one to test queries.

Let’s dissect what is happening here.

We want to test the write requests: AKA the Mutation resolvers.

As we are using graphql-spring-boot-starter-testwe are taking advantage of the embedded JUnit 5 Jupiter engine, and some useful tools to set up graphql easily.

Especially the @GraphQLTestannotation that is loading only a slice of the Spring-context that is needed for our tests to run.

This is particularly interesting as our tests need to run fast and not wait for the full heavy Spring context to load.

Another interesting tool is the GraphQLTestTemplate class that helps us send real GraphQL queries, that we have defined earlier, to tests our resolvers.

As we want our tests to run as fast as possible, we do not need to load the real underlying beans needed for our resolvers, talking here about the UserService bean. We will just mock them, and tell the mock how to behave when a specific method is called by the resolver.

Finally, as we have secured our GraphQL resources, we have to use Spring-security to mock users with adequate rights.

We are following the same logic for testing the read request resolvers, AKA : Query resolvers

And that’s all you have to do to test that your resolvers are responding to the requests you expect them to.

This is the end of the series, I hope you enjoyed it.

Thanks for reading.

Feedback is a gift 🎁.

Top comments (0)