Mocking and unit testing graphql-dotnet

Mocking and unit testing graphql-dotnet


0

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?

2

  • what did you try yourself?

    – MakePeaceGreatAgain

    42 mins ago

  • @MakePeaceGreatAgain multiple approaches by mocking the GraphQLHttpClient directly or by passing a mock version of the HttpClient. I ended up with a solution which I've described in the answer bellow (which I thing might be helpful for other users).

    – Dawid Rutkowski

    19 mins ago

2 Answers
2


0

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.

1

  • 1

    So, it seems like it comes down to mocking good old HttpMessageHandler, as is the case with all solutions using hardcoded depndency on HttpClient

    – Michał Turczyn

    52 mins ago


-1

Not sure if that’s possible in your scenario, but GraphQLHttpClient implements interface IGraphQLWebSocketClient, so you could use interface instead when declaring your dependency and then, you can easily mock the interface as usual.

1

  • Did you test it or try it by yourself? Or did you just check the source code and notice an interface there and that is all? What I've described in the answer is possible as I'm using it in multiple unit tests. What you are proposing is to use an interface which do not have methods which are mainly used from the GraphQLHttpClient.

    – Dawid Rutkowski

    21 mins ago




Leave a Reply

Your email address will not be published. Required fields are marked *