首页 新闻 会员 周边 捐助

C#/.NET: 求 mock HttpClient 的好姿势

0
悬赏园豆:30 [已解决问题] 解决于 2023-01-29 07:54

想在测试中 mock HttpClient,请问有什么以假乱真的好姿势?

dudu的主页 dudu | 高人七级 | 园豆:29622
提问于:2023-01-28 11:09
< >
分享
最佳答案
0

找到了一个好东东:Moq.Contrib.HttpClient

在测试中 mock HttpClient 的试验代码如下

[Theory]
[InlineData(1, 2, 3)]
public async Task GetPublicPostIds_test(params int[] postIds)
{
    var publicPostIds = postIds.ToList();
    publicPostIds.Remove(Random.Shared.Next(1, 3));

    var handler = new Mock<HttpMessageHandler>();
    var httpClient = handler.CreateClient();
    httpClient.BaseAddress = new Uri("http://blog_api");
    handler.SetupRequest(HttpMethod.Post, "http://blog_api/v2/blogposts/public/ids")
        .ReturnsJsonResponse(publicPostIds);

    var actualPostIds = await new BlogClient(httpClient, _logger).BlogPosts
        .GetPublicPostIds(postIds);
    Assert.NotEmpty(actualPostIds);
    actualPostIds.Should().BeEquivalentTo(publicPostIds);
} 
dudu | 高人七级 |园豆:29622 | 2023-01-29 07:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册