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
2 Answers
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ł Turczyn52 mins ago
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 Rutkowski21 mins ago
what did you try yourself?
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).
19 mins ago