正如标题所示,我有一些调用IHttpClientFactory.CreateClient()
来创建 HttpClient 实例的代码。
我在 .Net Core 3.1 中这样做
我需要嘲笑这个。根据这个问题“C# Mock IHttpclient & CreateClient”,以下应该可以工作......
[Test]
public void Mytest() {
var httpClientFactory = new Mock<IHttpClientFactory>(MockBehavior.Strict);
httpMessageHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
httpMessageHandler.Protected()
// Setup the PROTECTED method to mock
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
// prepare the expected response of the mocked http call
.ReturnsAsync(new HttpResponseMessage()
{
StatusCode = HttpStatusCode.BadRequest,
})
.Verifiable();
var httpClient = new HttpClient(httpMessageHandler.Object);
httpClientFactory.Setup(_ => _.CreateClient()) // This fails
.Returns(httpClient).Verifiable();
systemUnderTest = new MyService(httpClientFactory.Object);
var result = systemUnderTest.MyMethod()
// Assert Stuff
}
但是,当我运行它时,会报告以下内容...
System.NotSupportedException:不支持的表达式:_ => _.CreateClient() 扩展方法(此处为:HttpClientFactoryExtensions.CreateClient)不得用于设置/验证表达式。
我显然做错了什么,但我看不出它是什么。
任何人都可以提供任何指示吗?