本文整理汇总了C#中HttpMessageHandlerMock类的典型用法代码示例。如果您正苦于以下问题:C# HttpMessageHandlerMock类的具体用法?C# HttpMessageHandlerMock怎么用?C# HttpMessageHandlerMock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpMessageHandlerMock类属于命名空间,在下文中一共展示了HttpMessageHandlerMock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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) {
}
}
示例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");
}
示例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) {
}
}
示例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);
}
}
示例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);
}
示例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);
}
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}