Search code examples
c#unit-testinggraphqlmoqgraphql-dotnet

Mocking and unit testing graphql-dotnet


I'm using graphql-dotnet library to query some GraphQL APIs from my C# code. Is there a way to easily mock the GraphQLHttpClient in unit tests?


Solution

  • It's not easy to mock the GraphQLHttpClient directly but you can provide your own HttpClient in one of the GraphQLHttpClient constructors and mock the HttpMessageHandler. Take a look a the code below:

    HttpContent content = new StringContent(_responseContent, Encoding.UTF8, "application/json");
    var response = new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.OK,
        Content = content
    };
    
    var httpMessageHandler = new Mock<HttpMessageHandler>();
    httpMessageHandler.Protected()
                      .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
                      .ReturnsAsync(response);
    
    HttpClient client = new HttpClient(httpMessageHandler.Object);
    
    GraphQLHttpClient graphQlClient = new GraphQLHttpClient(GetOptions(), new NewtonsoftJsonSerializer(), client);
    

    The above code works fine and allows me to provide any testing JSON output of the real GQL API I want in the _responseContent variable. The first line and two arguments - Encoding.UTF8, "application/json" - are quite important. Without providing the content type, the GraphQLHttpClient will throw an exception because of this line. It took me a while to find it.

    I'm using Moq library for mocking objects.