Skip to content

Instantly share code, notes, and snippets.

@glyons
Last active July 27, 2018 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glyons/1bbf1449d489a2c61e262d9a501108b0 to your computer and use it in GitHub Desktop.
Save glyons/1bbf1449d489a2c61e262d9a501108b0 to your computer and use it in GitHub Desktop.
Async HttpClient Request Mock for Google.com
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Moq.Protected;
namespace whatever
{
[TestClass()]
public class BasicMockClientTests
{
[TestMethod]
public void MockGoogleComTest()
{
// Mock
var handler = new Mock<HttpMessageHandler>();
handler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.Returns(Task<HttpResponseMessage>.Factory.StartNew(() =>
{
return new HttpResponseMessage(HttpStatusCode.OK);
}))
.Callback<HttpRequestMessage, CancellationToken>((r, c) =>
{
Assert.AreEqual(HttpMethod.Get, r.Method);
});
using (var client = new HttpClient(handler.Object))
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://www.google.com");
var response = client.SendAsync(request).Result;
Console.WriteLine(response.StatusCode);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment