1
votes

In a quarkus project with quarkus-smallrye-graphql lib, is there a way to unit test a GraphQL resource object like this one :

@GraphQLApi
public class ProductResource {

    @Inject
    private ProductRepository productRepository;

    @Query("products")
    @Description("Get all Products")
    @RolesAllowed({"USER","ADMIN"})
    public List<Product> findAll() {
        return this.productRepository.findAll().list();
    }

    @Mutation
    @Description("Create a new Product")
    @RolesAllowed("ADMIN")
    public Boolean createProduct(String name, Double price) {
        return this.productRepository.createProduct(name, price);
    }
}

I want to be able to send a GraphQL query (with Authentication inactivated/or not) in unit testing in order to validate my annotations but I don't find any documented way to do it.

2

2 Answers

1
votes

If using plain HTTP requests for the communication is ok to you, then something like this would work

@QuarkusTest
public class ProductRepositoryTest {

    @Test
    public void testQuery() {
        RestAssured.given()
                .when()
                .contentType("application/json")
                .body("{ \"query\": \"{" +
                        "  products {" +
                        "    name" +
                        "    price" +
                        "  }" +
                        "}\"" +
                        "}")
                .post("/graphql")
                .then()
                .statusCode(200)
                .body("data.products", Matchers.not(Matchers.emptyArray()));
    }
}

There is also the option to use the typesafe GraphQL client from SmallRye GraphQL (see an example in my repo: https://github.com/jmartisk/mock-artifacts/tree/master/graphql/graphql-client) - it should be usable for testing purposes, even though it's very high level so you might lose some finer-grained functionality. Soon, there will also be a different type of client - the dynamic client, but SmallRye GraphQL doesn't support it yet.

0
votes

Last successful try :

  RestAssured.given()
                .when()
                .contentType("application/json")
                .body("{ \"query\": \"{" +
                        "  products {" +
                        "    name" +
                        "    price" +
                        "  }" +
                        "}\"" +
                        "}")
                .post("/graphql")
                .then().log().ifValidationFails()
                .statusCode(200)
                .body("data.products.name", Matchers.hasItems("Ten", "Twenty"))
                .body("data.products.price", Matchers.hasItems(Matchers.equalTo(10f), Matchers.equalTo(20f)));

NB: I've inactivated the security to make the unit tests work.