[Spring Boot] GraphQL with Spring Boot using graphql-spring-boot-starter
In this article, we will look at a sample Spring Boot application using Spring GraphQL Boot Starter. This example will cover how to implement controller for GraphQL schema and how to write test code.
According to the Spring GraphQL reference, the following dependency needs to be added to pom.xml
.
First of all, my GraphQL schema is defined:
Implementing Controller
There are a few rules we have to follow when mapping a GraphQL schema to a controller.
Query
types are mapped with@QueryMapping
Mutation
types are mapped with@MutationMapping
- Method names of the controller class need to match the type names (in this example
employees, departments, departmentById, updatedDepartmentName
) - Arguments are mapped with
@Argument
Putting these rules together, the controller implementation looks like:
The GraphQL endpoint can be tested with your favorite Rest Client tool (such as Insomnia, Postman, etc). By default, the GraphQL endpoint is at POST /graphql
.
Writing Tests
GraphQL endpoint can be tested with WebGraphQlTester
. The approach was to define some queries to test against and use them in test cases. Of course queries can be typed up in string if preferred.
This test code consists of one query type and one mutation type. The full test code looks like below:
Lastly, here are test queries: