Last active
July 27, 2018 06:59
-
-
Save glyons/1bbf1449d489a2c61e262d9a501108b0 to your computer and use it in GitHub Desktop.
Async HttpClient Request Mock for Google.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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