我正在使用 graphql-dotnet 库从我的 C# 代码中查询一些 GraphQL API。有没有办法在单元测试中轻松模拟
GraphQLHttpClient
?
直接模拟
GraphQLHttpClient
并不容易,但您可以在 HttpClient
构造函数之一中提供自己的 GraphQLHttpClient
并模拟 HttpMessageHandler
。看看下面的代码:
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);
上面的代码工作正常,并允许我在
_responseContent
变量中提供我想要的真实 GQL API 的任何测试输出。
第一行和两个参数 - Encoding.UTF8, "application/json"
- 非常重要。如果不提供内容类型,GraphQLHttpClient 将因此行而引发异常。我花了一段时间才找到它。
我正在使用
Moq
库来模拟对象。