Skip to content

Instantly share code, notes, and snippets.

@xbotter
Created May 19, 2023 06:10
Show Gist options
  • Save xbotter/f50c7dd0855b4321ef5d1fe6f5b02abb to your computer and use it in GitHub Desktop.
Save xbotter/f50c7dd0855b4321ef5d1fe6f5b02abb to your computer and use it in GitHub Desktop.
如何Mock一个HttpClient
var httpClientMock = new Mock<HttpClient>();
// Set up the SendAsync method to return a desired response
httpClientMock
.Setup(x => x.SendAsync(It.IsAny<HttpRequestMessage>(), CancellationToken.None))
.ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK));
// Set up the SendAsync method to match a specific URL and return a desired response
httpClientMock
.Setup(x => x.SendAsync(It.Is<HttpRequestMessage>(req => req.RequestUri.AbsoluteUri == "https://example.com/api/data"), CancellationToken.None))
.ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Mocked response") });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment