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:

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

You can check 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.




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


GraphQL Mutation Test example

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-test we 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


GraphQL Query test example

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.

Thanks for reading.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Philippe Simo

FULLSTACK DEVELOPER, FOUNDER, and CEO of zerofiltre.tech: A company that aims to provide technology services and transform people’s lives with code.