荣耀彩票代理

  • 热门专题

在ASP.NET Core里如何使用HttpClient为对象的类编写单元测试

作者:wy  发布日期:2019-01-09 08:39:00
  •   我相信大家对于在ASP.NET Core里如何以使用HttpClient为对象的类编写单元测试很感兴趣,在此篇文章中我们详细的将案例、步骤、过程都一步一步的记录在此,希望你看到这篇文章能够有所收获。

      JINIANQIAN,WEIRUANYINRULEHttpClientLEILAITIDAIHttpWebRequestLAIFASONGWebQINGQIU。ZHEIGEXINDELEIGENGYIYUSHIYONG,GENGJIAJIANJIE,GENGJUYOUYIBUXING,QIEYIYUKUOZHAN。

    荣耀彩票代理  HttpClientLEIYOUYIGEKEYIJIESHOUHttpMessageHandlerLEIDUIXIANGDEGOUZAOHANSHU。HttpMessageHandlerLEIDUIXIANGKEYIJIESHOUYIGEQINGQIU(HttpRequestMessage), BINGFANHUIXIANGYING(HttpResponseMessage)。TADEGONGNENGWANQUANQUJUEYUTADESHIXIAN。MORENQINGKUANGXIAHttpClientSHIYONGDESHIHttpClientHandler,HttpClientHandlerSHIYIGECHULICHENGXU,TAXIANGWANGLUOFUWUQIFASONGQINGQIUBINGCONGFUWUQIFANHUIXIANGYING。ZAIBENPIANBOWENZHONG,WOMENJIANGTONGGUOJICHENGDelegatingHandlerLAICHUANGJIANZIJIDEHttpMessageHandler。

    荣耀彩票代理  WEILESHIXIANYISHANGGONGNENG,HttpClientDUIXIANGBUKEYIZHIJIESHIYONG,ERSHIXUYAOYUYUNXUSHIYONGIHttpClientFactoryJIEKOUJINXINGMONIDEYILAIZHURUYIQISHIYONG。

    荣耀彩票代理  RANGWOMENLAIWEIZAOYIGEHttpMessageHandler

      XIAMIANDELIZIZHONG,WOMENZHITAOLUNHttpResponseMessage, BUHUICHULIHttpRequestMessage。

    荣耀彩票代理  YIXIASHIWOWEIZAODEYIGEHttpMessageHandlerDUIXIANG。

    荣耀彩票代理  public class FakeHttpMessageHandler : DelegatingHandler

      {

    荣耀彩票代理  private HttpResponseMessage _fakeResponse;

    荣耀彩票代理  public FakeHttpMessageHandler(HttpResponseMessage responseMessage)

      {

      _fakeResponse = responseMessage;

      }

      protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

      {

      return await Task.FromResult(_fakeResponse);

      }

      }

    荣耀彩票代理  ZHEILIWOTIANJIALEYIGEXUYAOHttpResponseMessageGOUZAOHANSHU,RANHOUFUXIELESendAsyncFANGFA, ZAIGAIFANGFAZHONGZHIJIEFANHUILEGOUZAOHANSHUZHONGCHUANRUDEHttpResponseMessageDUIXIANG。

    荣耀彩票代理  BIANXIEYIGESHIYONGIHttpClientFactoryJIEKOUDEFUWU

    ASP.NET

      XIAMIANWOMENXUYAOBIANXIEYIGEUserServiceLEI,ZHEIGELEITIGONGLEYIGEGetUsersFANGFA,LAICONGYUANCHENGFUWUQIDUANHUOQUYONGHULIEBIAO。

      public class UserService

      {

    荣耀彩票代理  private readonly IHttpClientFactory _httpFactory;

      public UserService(IHttpClientFactory httpFactory)

      {

      _httpFactory = httpFactory;

      }

      public async Task> GetUsers(string url)

      {

      using (HttpClient httpclient = _httpFactory.CreateClient())

      {

      using (HttpResponseMessage response = await httpclient.GetAsync(url))

      {

      if (response.StatusCode == HttpStatusCode.OK)

      {

      List users = await response.Content.ReadAsAsync>();

      return users;

      }

      return null;

      }

      }

      }

      }

      YIXIASHIApiQINGQIUFANHUIDEYONGHULEI

    荣耀彩票代理  public class User

      {

    荣耀彩票代理  public string FirstName { get; set; }

      public string LastName { get; set; }

      }

    荣耀彩票代理  RUNISUOJIAN,SHIYONGHttpClientFactoryYUNXUWOMENMONIHttpClientSHILIHUA

      CESHIFUWU

      ZAIXIAMIANDEDANYUANCESHIZHONG,WOMENHUISHIYONGXUnit、FluentAssertion、NSubstitute

      CESHICHANGJING1: MONIYIGEQINGQIU,FANHUI2GEYONGHU

      public class UserServiceTests

      {

      [Fact]

    荣耀彩票代理  public async Task WhenACorrectUrlIsProvided_ServiceShouldReturnAlistOfUsers()

      {

    荣耀彩票代理  // Arrange

      var users = new List

      {

      new User

      {

      FirstName = "John",

    荣耀彩票代理  LastName = "Doe"

      },

      new User

      {

      FirstName = "John",

      LastName = "Deere"

      }

      };

      var httpClientFactoryMock = Substitute.For();

      var url = "http://good.uri";

    荣耀彩票代理  var fakeHttpMessageHandler = new FakeHttpMessageHandler(new HttpResponseMessage() {

      StatusCode = HttpStatusCode.OK,

      Content = new StringContent(JsonConvert.SerializeObject(users), Encoding.UTF8, "application/json")

      });

    荣耀彩票代理  var fakeHttpClient = new HttpClient(fakeHttpMessageHandler);

      httpClientFactoryMock.CreateClient().Returns(fakeHttpClient);

      // Act

      var service = new UserService(httpClientFactoryMock);

      var result = await service.GetUsers(url);

    荣耀彩票代理  // Assert

      result

      .Should()

      .BeOfType>()

      .And

      .HaveCount(2)

      .And

    荣耀彩票代理  .Contain(x => x.FirstName == "John")

      .And

      .Contain(x => x.LastName == "Deere")

      .And

      .Contain(x => x.LastName == "Doe");

      }

      }

      •ZAIYISHANGCESHIZHONG,WOMENQIWANGHUOQUYIGECHENGGONGDEXIANGYING,BINGDEDAO2GEYONGHUDEXINXI。

      •WOMENQIWANGCONGServiceZHONGDEDAODESHUJUSHIJSONGESHIDE。

      •WOMENSHIYONGYIGEWEIZAODECHULICHENGXUCHUSHIHUALEYIGEHttpClientDUIXIANG,RANHOUDINGYILEWOMENQIWANGDEDEDAODEWEIZAODUIXIANGhttpClientFactoryMock.CreateClient().Returns(fakeHttpClient);

    荣耀彩票代理  CESHICHANGJING2: MONIYIGE404CUOWU,FANHUIKONGSHUJU

    荣耀彩票代理  public class UserServiceTests

      {

      [Fact]

      public async Task WhenABadUrlIsProvided_ServiceShouldReturnNull()

      {

      // Arrange

      var httpClientFactoryMock = Substitute.For();

    荣耀彩票代理  var url = "http://bad.uri";

      var fakeHttpMessageHandler = new FakeHttpMessageHandler(new HttpResponseMessage() {

    荣耀彩票代理  StatusCode = HttpStatusCode.NotFound

      });

    荣耀彩票代理  var fakeHttpClient = new HttpClient(fakeHttpMessageHandler);

      httpClientFactoryMock.CreateClient().Returns(fakeHttpClient);

      // Act

      var service = new UserService(httpClientFactoryMock);

      var result = await service.GetUsers(url);

      // Assert

      result

      .Should()

      .BeNullOrEmpty();

      }

      }

      HECESHICHANGJING1LEISI,DANGYIGEHttpQINGQIUFANHUINot Found, TADEJIEGUOJISHINull

    荣耀彩票代理  BUZHIDAONIKANWANZHIHOUYOUHEGANXIANGNI?YOUMEIYOUSHOUHUODAOSHENMEXINDEZHISHI,ZIJIDECAOZUOSHIFOUYEWANCHENGLENI?XIWANGDAJIAYIHOUYEDUODUOZHICHIWOMENWANGZHAN,ZHEILIYOUXUDUOFENGFUDEZIXUN,RANGNIDABAOYANFUE。

About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规