Skip to content

Instantly share code, notes, and snippets.

@Jaecen
Created February 22, 2017 00:53
Show Gist options
  • Save Jaecen/730279a9807678d682726c4b2af6ccbb to your computer and use it in GitHub Desktop.
Save Jaecen/730279a9807678d682726c4b2af6ccbb to your computer and use it in GitHub Desktop.
Mocking HttpClient
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DotUpgrade.Test
{
class AlwaysReturns : HttpMessageHandler
{
readonly HttpStatusCode StatusCode;
public AlwaysReturns(HttpStatusCode statusCode)
{
StatusCode = statusCode;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
=> Task.FromResult(new HttpResponseMessage(StatusCode));
}
}
using System.Net;
using System.Net.Http;
using Xunit;
namespace DotUpgrade.Test
{
public class SampleTests
{
[Fact]
public void Should_Return_Indicated_Code()
{
var httpClient = new HttpClient(new AlwaysReturns(HttpStatusCode.Conflict));
var response = httpClient.GetAsync("http://www.google.com").Result;
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment