Created
May 19, 2023 06:10
-
-
Save xbotter/f50c7dd0855b4321ef5d1fe6f5b02abb to your computer and use it in GitHub Desktop.
如何Mock一个HttpClient
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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