• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# HttpMessageHandlerMock类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中HttpMessageHandlerMock的典型用法代码示例。如果您正苦于以下问题:C# HttpMessageHandlerMock类的具体用法?C# HttpMessageHandlerMock怎么用?C# HttpMessageHandlerMock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



HttpMessageHandlerMock类属于命名空间,在下文中一共展示了HttpMessageHandlerMock类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: GetThumbnailInfoAsync_RequestTest

        public async Task GetThumbnailInfoAsync_RequestTest()
        {
            var handler = new HttpMessageHandlerMock();

            handler.Enqueue(x =>
            {
                Assert.Equal(HttpMethod.Get, x.Method);
                Assert.Equal("https://api.tumblr.com/v2/blog/hoge.tumblr.com/posts",
                    x.RequestUri.GetLeftPart(UriPartial.Path));

                var query = HttpUtility.ParseQueryString(x.RequestUri.Query);

                Assert.Equal(ApplicationSettings.TumblrConsumerKey, query["api_key"]);
                Assert.Equal("1234567", query["id"]);

                return new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(@"{
  ""meta"": { ""status"": 200, ""msg"": ""OK"" },
  ""response"": { ""blog"": { }, ""posts"": { } }
}"),
                };
            });

            using (var http = new HttpClient(handler))
            {
                var service = new Tumblr(http);

                var url = "http://hoge.tumblr.com/post/1234567/tetetete";
                var thumb = await service.GetThumbnailInfoAsync(url, null, CancellationToken.None)
                    .ConfigureAwait(false);
            }

            Assert.Equal(0, handler.QueueCount);
        }
开发者ID:nezuku,项目名称:OpenTween,代码行数:35,代码来源:TumblrTest.cs


示例2: GetAsync_Test

        public async Task GetAsync_Test()
        {
            using (var mockHandler = new HttpMessageHandlerMock())
            using (var http = new HttpClient(mockHandler))
            using (var apiConnection = new TwitterApiConnection("", ""))
            {
                apiConnection.http = http;

                mockHandler.Enqueue(x =>
                {
                    Assert.Equal(HttpMethod.Get, x.Method);
                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
                        x.RequestUri.GetLeftPart(UriPartial.Path));

                    var query = HttpUtility.ParseQueryString(x.RequestUri.Query);

                    Assert.Equal("1111", query["aaaa"]);
                    Assert.Equal("2222", query["bbbb"]);

                    return new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent("\"hogehoge\""),
                    };
                });

                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
                var param = new Dictionary<string, string>
                {
                    ["aaaa"] = "1111",
                    ["bbbb"] = "2222",
                };

                var result = await apiConnection.GetAsync<string>(endpoint, param, endpointName: "/hoge/tetete")
                    .ConfigureAwait(false);
                Assert.Equal("hogehoge", result);

                Assert.Equal(0, mockHandler.QueueCount);
            }
        }
开发者ID:opentween,项目名称:OpenTween,代码行数:39,代码来源:TwitterApiConnectionTest.cs


示例3: TranslateAsync_Test

        public async Task TranslateAsync_Test()
        {
            using (var mockHandler = new HttpMessageHandlerMock())
            using (var http = new HttpClient(mockHandler))
            {
                var mock = new Mock<MicrosoftTranslatorApi>(http);
                mock.Setup(x => x.GetAccessTokenAsync())
                    .ReturnsAsync(Tuple.Create("1234abcd", TimeSpan.FromSeconds(1000)));

                var translateApi = mock.Object;

                mockHandler.Enqueue(x =>
                {
                    Assert.Equal(HttpMethod.Get, x.Method);
                    Assert.Equal(MicrosoftTranslatorApi.TranslateEndpoint.AbsoluteUri,
                        x.RequestUri.GetLeftPart(UriPartial.Path));

                    var query = HttpUtility.ParseQueryString(x.RequestUri.Query);

                    Assert.Equal("hogehoge", query["text"]);
                    Assert.Equal("ja", query["to"]);
                    Assert.Equal("en", query["from"]);

                    return new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent("ほげほげ"),
                    };
                });

                var result = await translateApi.TranslateAsync("hogehoge", langTo: "ja", langFrom: "en")
                    .ConfigureAwait(false);
                Assert.Equal("ほげほげ", result);

                mock.Verify(x => x.GetAccessTokenAsync(), Times.Once());
                Assert.Equal(0, mockHandler.QueueCount);
            }
        }
开发者ID:opentween,项目名称:OpenTween,代码行数:37,代码来源:MicrosoftTranslatorApiTest.cs


示例4: GetThumbnailInfoAsync_RequestWithSignatureTest

        public async Task GetThumbnailInfoAsync_RequestWithSignatureTest()
        {
            var handler = new HttpMessageHandlerMock();
            using (var http = new HttpClient(handler))
            {
                var service = new FoursquareCheckin(http);

                handler.Enqueue(x =>
                {
                    Assert.Equal(HttpMethod.Get, x.Method);
                    Assert.Equal("https://api.foursquare.com/v2/checkins/xxxxxxxx",
                        x.RequestUri.GetLeftPart(UriPartial.Path));

                    var query = HttpUtility.ParseQueryString(x.RequestUri.Query);

                    Assert.Equal(ApplicationSettings.FoursquareClientId, query["client_id"]);
                    Assert.Equal(ApplicationSettings.FoursquareClientSecret, query["client_secret"]);
                    Assert.NotNull(query["v"]);
                    Assert.Equal("aaaaaaa", query["signature"]);

                    // リクエストに対するテストなのでレスポンスは適当に返す
                    return new HttpResponseMessage(HttpStatusCode.NotFound);
                });

                var post = new PostClass
                {
                    PostGeo = new PostClass.StatusGeo { },
                };

                var thumb = await service.GetThumbnailInfoAsync(
                    "https://foursquare.com/hogehoge/checkin/xxxxxxxx?s=aaaaaaa",
                    post, CancellationToken.None);

                Assert.Equal(0, handler.QueueCount);
            }
        }
开发者ID:egcube,项目名称:OpenTween,代码行数:36,代码来源:FoursquareCheckinTest.cs


示例5: GetThumbnailInfoAsync_GeoLocatedTweetTest

        public async Task GetThumbnailInfoAsync_GeoLocatedTweetTest()
        {
            var handler = new HttpMessageHandlerMock();
            using (var http = new HttpClient(handler))
            {
                var service = new FoursquareCheckin(http);

                handler.Enqueue(x =>
                {
                    // このリクエストは実行されないはず
                    Assert.True(false);
                    return new HttpResponseMessage(HttpStatusCode.NotFound);
                });

                // 既にジオタグが付いているツイートに対しては何もしない
                var post = new PostClass
                {
                    PostGeo = new PostClass.StatusGeo
                    {
                        Lat = 34.35067978344854,
                        Lng = 134.04693603515625,
                    },
                };

                var thumb = await service.GetThumbnailInfoAsync(
                    "https://foursquare.com/hogehoge/checkin/xxxxxxxx?s=aaaaaaa",
                    post, CancellationToken.None);

                Assert.Equal(1, handler.QueueCount);
            }
        }
开发者ID:egcube,项目名称:OpenTween,代码行数:31,代码来源:FoursquareCheckinTest.cs


示例6: GetAsync_ErrorStatusTest

        public async Task GetAsync_ErrorStatusTest()
        {
            using (var mockHandler = new HttpMessageHandlerMock())
            using (var http = new HttpClient(mockHandler))
            using (var apiConnection = new TwitterApiConnection("", ""))
            {
                apiConnection.http = http;

                mockHandler.Enqueue(x =>
                {
                    return new HttpResponseMessage(HttpStatusCode.BadGateway)
                    {
                        Content = new StringContent("### Invalid JSON Response ###"),
                    };
                });

                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);

                var exception = await Assert.ThrowsAsync<TwitterApiException>(() => apiConnection.GetAsync<string>(endpoint, null, endpointName: "/hoge/tetete"))
                    .ConfigureAwait(false);

                // エラーレスポンスの読み込みに失敗した場合はステータスコードをそのままメッセージに使用する
                Assert.Equal("BadGateway", exception.Message);
                Assert.Null(exception.ErrorResponse);

                Assert.Equal(0, mockHandler.QueueCount);
            }
        }
开发者ID:opentween,项目名称:OpenTween,代码行数:28,代码来源:TwitterApiConnectionTest.cs


示例7: Send_SameMessage

		public void Send_SameMessage ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");

			mh.OnSend = l => {
				return new HttpResponseMessage ();
			};

			client.Send (request);
			try {
				client.Send (request);
			} catch (InvalidOperationException) {
			}
		}
开发者ID:rnagy,项目名称:mono-1,代码行数:17,代码来源:HttpClientTest.cs


示例8: Send_DefaultRequestHeaders

		public void Send_DefaultRequestHeaders ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			client.DefaultRequestHeaders.Referrer = new Uri ("http://google.com");

			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			var response = new HttpResponseMessage ();

			mh.OnSend = l => {
				Assert.AreEqual (client.DefaultRequestHeaders.Referrer, l.Headers.Referrer, "#2");
				Assert.IsNotNull (l.Headers.Referrer, "#3");
				return Task.FromResult (response);
			};

			Assert.AreEqual (response, client.SendAsync (request).Result, "#1");
		}
开发者ID:bl8,项目名称:mono,代码行数:18,代码来源:HttpClientTest.cs


示例9: Send_InvalidHandler

		public void Send_InvalidHandler ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			client.BaseAddress = new Uri ("http://xamarin.com");
			var request = new HttpRequestMessage ();

			mh.OnSend = l => {
				Assert.AreEqual (l, request, "#1");
				return null;
			};

			try {
				// Broken by design
				client.SendAsync (request).Wait (WaitTimeout);
				Assert.Fail ("#2");
			} catch (Exception) {
			}
		}
开发者ID:bl8,项目名称:mono,代码行数:20,代码来源:HttpClientTest.cs


示例10: PostJsonAsync_Test

        public async Task PostJsonAsync_Test()
        {
            using (var mockHandler = new HttpMessageHandlerMock())
            using (var http = new HttpClient(mockHandler))
            using (var apiConnection = new TwitterApiConnection("", ""))
            {
                apiConnection.http = http;

                mockHandler.Enqueue(async x =>
                {
                    Assert.Equal(HttpMethod.Post, x.Method);
                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
                        x.RequestUri.AbsoluteUri);

                    Assert.Equal("application/json; charset=utf-8", x.Content.Headers.ContentType.ToString());

                    var body = await x.Content.ReadAsStringAsync()
                        .ConfigureAwait(false);

                    Assert.Equal("{\"aaaa\": 1111}", body);

                    return new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent("\"hogehoge\""),
                    };
                });

                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);

                await apiConnection.PostJsonAsync(endpoint, "{\"aaaa\": 1111}")
                    .ConfigureAwait(false);

                Assert.Equal(0, mockHandler.QueueCount);
            }
        }
开发者ID:opentween,项目名称:OpenTween,代码行数:35,代码来源:TwitterApiConnectionTest.cs


示例11: CancelPendingRequests_BeforeSend

		public void CancelPendingRequests_BeforeSend ()
		{
			var ct = new CancellationTokenSource ();
			ct.Cancel ();
			var rr = CancellationTokenSource.CreateLinkedTokenSource (new CancellationToken (), ct.Token);


			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			client.CancelPendingRequests ();

			mh.OnSendFull = (l, c) => {
				Assert.IsFalse (c.IsCancellationRequested, "#30");
				return Task.FromResult (new HttpResponseMessage ());
			};

			client.SendAsync (request).Wait (WaitTimeout);

			request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			client.SendAsync (request).Wait (WaitTimeout);
		}
开发者ID:bl8,项目名称:mono,代码行数:23,代码来源:HttpClientTest.cs


示例12: PostLazyAsync_MultipartTest

        public async Task PostLazyAsync_MultipartTest()
        {
            using (var mockHandler = new HttpMessageHandlerMock())
            using (var http = new HttpClient(mockHandler))
            using (var apiConnection = new TwitterApiConnection("", ""))
            {
                apiConnection.httpUpload = http;

                using (var image = TestUtils.CreateDummyImage())
                using (var media = new MemoryImageMediaItem(image))
                {
                    mockHandler.Enqueue(async x =>
                    {
                        Assert.Equal(HttpMethod.Post, x.Method);
                        Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
                            x.RequestUri.AbsoluteUri);

                        Assert.IsType<MultipartFormDataContent>(x.Content);

                        var boundary = x.Content.Headers.ContentType.Parameters.Cast<NameValueHeaderValue>()
                            .First(y => y.Name == "boundary").Value;

                        // 前後のダブルクオーテーションを除去
                        boundary = boundary.Substring(1, boundary.Length - 2);

                        var expectedText =
                            $"--{boundary}\r\n" +
                            "Content-Type: text/plain; charset=utf-8\r\n" +
                            "Content-Disposition: form-data; name=aaaa\r\n" +
                            "\r\n" +
                            "1111\r\n"+
                            $"--{boundary}\r\n" +
                            "Content-Type: text/plain; charset=utf-8\r\n" +
                            "Content-Disposition: form-data; name=bbbb\r\n" +
                            "\r\n" +
                            "2222\r\n" +
                            $"--{boundary}\r\n" +
                            $"Content-Disposition: form-data; name=media1; filename={media.Name}; filename*=utf-8''{media.Name}\r\n" +
                            "\r\n";

                        var expected = Encoding.UTF8.GetBytes(expectedText)
                            .Concat(image.Stream.ToArray())
                            .Concat(Encoding.UTF8.GetBytes($"\r\n--{boundary}--\r\n"));

                        Assert.Equal(expected, await x.Content.ReadAsByteArrayAsync().ConfigureAwait(false));

                        return new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new StringContent("\"hogehoge\""),
                        };
                    });

                    var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
                    var param = new Dictionary<string, string>
                    {
                        ["aaaa"] = "1111",
                        ["bbbb"] = "2222",
                    };
                    var mediaParam = new Dictionary<string, IMediaItem>
                    {
                        ["media1"] = media,
                    };

                    var result = await apiConnection.PostLazyAsync<string>(endpoint, param, mediaParam)
                        .ConfigureAwait(false);

                    Assert.Equal("hogehoge", await result.LoadJsonAsync()
                        .ConfigureAwait(false));

                    Assert.Equal(0, mockHandler.QueueCount);
                }
            }
        }
开发者ID:opentween,项目名称:OpenTween,代码行数:73,代码来源:TwitterApiConnectionTest.cs


示例13: PostLazyAsync_Multipart_NullTest

        public async Task PostLazyAsync_Multipart_NullTest()
        {
            using (var mockHandler = new HttpMessageHandlerMock())
            using (var http = new HttpClient(mockHandler))
            using (var apiConnection = new TwitterApiConnection("", ""))
            {
                apiConnection.httpUpload = http;

                mockHandler.Enqueue(async x =>
                {
                    Assert.Equal(HttpMethod.Post, x.Method);
                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
                        x.RequestUri.AbsoluteUri);

                    Assert.IsType<MultipartFormDataContent>(x.Content);

                    var boundary = x.Content.Headers.ContentType.Parameters.Cast<NameValueHeaderValue>()
                        .First(y => y.Name == "boundary").Value;

                    // 前後のダブルクオーテーションを除去
                    boundary = boundary.Substring(1, boundary.Length - 2);

                    var expectedText =
                        $"--{boundary}\r\n" +
                        $"\r\n--{boundary}--\r\n";

                    var expected = Encoding.UTF8.GetBytes(expectedText);

                    Assert.Equal(expected, await x.Content.ReadAsByteArrayAsync().ConfigureAwait(false));

                    return new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent("\"hogehoge\""),
                    };
                });

                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);

                var result = await apiConnection.PostLazyAsync<string>(endpoint, param: null, media: null)
                    .ConfigureAwait(false);

                Assert.Equal("hogehoge", await result.LoadJsonAsync()
                    .ConfigureAwait(false));

                Assert.Equal(0, mockHandler.QueueCount);
            }
        }
开发者ID:opentween,项目名称:OpenTween,代码行数:47,代码来源:TwitterApiConnectionTest.cs


示例14: PostLazyAsync_Test

        public async Task PostLazyAsync_Test()
        {
            using (var mockHandler = new HttpMessageHandlerMock())
            using (var http = new HttpClient(mockHandler))
            using (var apiConnection = new TwitterApiConnection("", ""))
            {
                apiConnection.http = http;

                mockHandler.Enqueue(async x =>
                {
                    Assert.Equal(HttpMethod.Post, x.Method);
                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
                        x.RequestUri.AbsoluteUri);

                    var body = await x.Content.ReadAsStringAsync()
                        .ConfigureAwait(false);
                    var query = HttpUtility.ParseQueryString(body);

                    Assert.Equal("1111", query["aaaa"]);
                    Assert.Equal("2222", query["bbbb"]);

                    return new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent("\"hogehoge\""),
                    };
                });

                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
                var param = new Dictionary<string, string>
                {
                    ["aaaa"] = "1111",
                    ["bbbb"] = "2222",
                };

                var result = await apiConnection.PostLazyAsync<string>(endpoint, param)
                    .ConfigureAwait(false);

                Assert.Equal("hogehoge", await result.LoadJsonAsync()
                    .ConfigureAwait(false));

                Assert.Equal(0, mockHandler.QueueCount);
            }
        }
开发者ID:opentween,项目名称:OpenTween,代码行数:43,代码来源:TwitterApiConnectionTest.cs


示例15: GetStreamAsync_Test

        public async Task GetStreamAsync_Test()
        {
            using (var mockHandler = new HttpMessageHandlerMock())
            using (var http = new HttpClient(mockHandler))
            using (var apiConnection = new TwitterApiConnection("", ""))
            using (var image = TestUtils.CreateDummyImage())
            {
                apiConnection.http = http;

                mockHandler.Enqueue(x =>
                {
                    Assert.Equal(HttpMethod.Get, x.Method);
                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
                        x.RequestUri.GetLeftPart(UriPartial.Path));

                    var query = HttpUtility.ParseQueryString(x.RequestUri.Query);

                    Assert.Equal("1111", query["aaaa"]);
                    Assert.Equal("2222", query["bbbb"]);

                    return new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ByteArrayContent(image.Stream.ToArray()),
                    };
                });

                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
                var param = new Dictionary<string, string>
                {
                    ["aaaa"] = "1111",
                    ["bbbb"] = "2222",
                };

                var stream = await apiConnection.GetStreamAsync(endpoint, param)
                    .ConfigureAwait(false);

                using (var memoryStream = new MemoryStream())
                {
                    // 内容の比較のために MemoryStream にコピー
                    await stream.CopyToAsync(memoryStream).ConfigureAwait(false);

                    Assert.Equal(image.Stream.ToArray(), memoryStream.ToArray());
                }

                Assert.Equal(0, mockHandler.QueueCount);
            }
        }
开发者ID:opentween,项目名称:OpenTween,代码行数:47,代码来源:TwitterApiConnectionTest.cs


示例16: GetAsync_ErrorJsonTest

        public async Task GetAsync_ErrorJsonTest()
        {
            using (var mockHandler = new HttpMessageHandlerMock())
            using (var http = new HttpClient(mockHandler))
            using (var apiConnection = new TwitterApiConnection("", ""))
            {
                apiConnection.http = http;

                mockHandler.Enqueue(x =>
                {
                    return new HttpResponseMessage(HttpStatusCode.Forbidden)
                    {
                        Content = new StringContent("{\"errors\":[{\"code\":187,\"message\":\"Status is a duplicate.\"}]}"),
                    };
                });

                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);

                var exception = await Assert.ThrowsAsync<TwitterApiException>(() => apiConnection.GetAsync<string>(endpoint, null, endpointName: "/hoge/tetete"))
                    .ConfigureAwait(false);

                // エラーレスポンスの JSON に含まれるエラーコードに基づいてメッセージを出力する
                Assert.Equal("DuplicateStatus", exception.Message);

                Assert.Equal(TwitterErrorCode.DuplicateStatus, exception.ErrorResponse.Errors[0].Code);
                Assert.Equal("Status is a duplicate.", exception.ErrorResponse.Errors[0].Message);

                Assert.Equal(0, mockHandler.QueueCount);
            }
        }
开发者ID:opentween,项目名称:OpenTween,代码行数:30,代码来源:TwitterApiConnectionTest.cs


示例17: Send_BaseAddress

		public void Send_BaseAddress ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			client.BaseAddress = new Uri ("http://localhost/");
			var response = new HttpResponseMessage ();

			mh.OnSend = l => {
				Assert.AreEqual ("http://localhost/relative", l.RequestUri.ToString (), "#2");
				return Task.FromResult (response);
			};

			Assert.AreEqual (response, client.GetAsync ("relative").Result, "#1");
			Assert.AreEqual (response, client.GetAsync ("/relative").Result, "#2");
		}
开发者ID:rodrmoya,项目名称:mono,代码行数:16,代码来源:HttpClientTest.cs


示例18: SetResponse

 public void SetResponse(HttpResponseMessage response)
 {
     HttpMessageHandler = new HttpMessageHandlerMock(response);
 }
开发者ID:gitter-badger,项目名称:vika,代码行数:4,代码来源:MockHttpClientFactory.cs


示例19: CancelPendingRequests

		public void CancelPendingRequests ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			var mre = new ManualResetEvent (false);

			mh.OnSendFull = (l, c) => {
				mre.Set ();
				Assert.IsTrue (c.WaitHandle.WaitOne (1000), "#20");
				Assert.IsTrue (c.IsCancellationRequested, "#21");
				mre.Set ();
				return Task.FromResult (new HttpResponseMessage ());
			};

			var t = Task.Factory.StartNew (() => {
				client.SendAsync (request).Wait (WaitTimeout);
			});

			Assert.IsTrue (mre.WaitOne (500), "#1");
			mre.Reset ();
			client.CancelPendingRequests ();
			Assert.IsTrue (t.Wait (500), "#2");

			request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			mh.OnSendFull = (l, c) => {
				Assert.IsFalse (c.IsCancellationRequested, "#30");
				return Task.FromResult (new HttpResponseMessage ());
			};

			client.SendAsync (request).Wait (WaitTimeout);
		}
开发者ID:bl8,项目名称:mono,代码行数:33,代码来源:HttpClientTest.cs


示例20: GetAccessTokenAsync_Test

        public async Task GetAccessTokenAsync_Test()
        {
            using (var mockHandler = new HttpMessageHandlerMock())
            using (var http = new HttpClient(mockHandler))
            {
                var translateApi = new MicrosoftTranslatorApi(http);

                mockHandler.Enqueue(async x =>
                {
                    Assert.Equal(HttpMethod.Post, x.Method);
                    Assert.Equal(MicrosoftTranslatorApi.OAuthEndpoint, x.RequestUri);

                    var body = await x.Content.ReadAsStringAsync()
                        .ConfigureAwait(false);
                    var query = HttpUtility.ParseQueryString(body);

                    Assert.Equal("client_credentials", query["grant_type"]);
                    Assert.Equal(ApplicationSettings.AzureClientId, query["client_id"]);
                    Assert.Equal(ApplicationSettings.AzureClientSecret, query["client_secret"]);
                    Assert.Equal("http://api.microsofttranslator.com", query["scope"]);

                    return new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(@"
{
  ""access_token"": ""12345acbde"",
  ""token_type"": ""bearer"",
  ""expires_in"": 3600
}"),
                    };
                });

                var result = await translateApi.GetAccessTokenAsync()
                    .ConfigureAwait(false);

                var expectedToken = Tuple.Create(@"12345acbde", TimeSpan.FromSeconds(3600));
                Assert.Equal(expectedToken, result);

                Assert.Equal(0, mockHandler.QueueCount);
            }
        }
开发者ID:opentween,项目名称:OpenTween,代码行数:41,代码来源:MicrosoftTranslatorApiTest.cs



注:本文中的HttpMessageHandlerMock类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# HttpMethod类代码示例发布时间:2022-05-24
下一篇:
C# HttpListenerContext类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap