如何在单元测试中使用FttItEasy和HttpClient?

时间:2014-03-07 00:42:52

标签: c# .net unit-testing fakeiteasy

我正在试图弄清楚如何在HttpClient中使用FakeItEasy,给出以下代码:

public Foo(string key, HttpClient httpClient = null)
{ .. }

public void DoGet()
{
    ....

    if (_httpClient == null)
    {
        _httpClient = new HttpClient();
    }

    var response = _httpClient.GetAsync("user/1);
}

public void DoPost(foo Foo)
{
    if (_httpClient == null)
    {
        _httpClient = new HttpClient();
    }

    var formData = new Dictionary<string, string>
    {
        {"Name", "Joe smith"},
        {"Age", "40"}
    };    

    var response = _httpClient.PostAsync("user", 
        new FormUrlEncodedContent(formData));
}

所以我不确定如何使用FakeItEasy假冒HttpClient的GetAsyncPostAsync方法。

生产代码不会在HttpClient中传递,但是单元测试将传递由FakeItEasy制作的虚假实例。

例如。

[Fact]
public void GivenBlah_DoGet_DoesSomething()
{
    // Arrange.
    var httpClient A.Fake<HttpClient>(); // <-- need help here.
    var foo = new Foo("aa", httpClient);

    // Act.
    foo.DoGet();

    // Assert....
}

更新

我认为FiE(以及大多数模拟包)都适用于接口或虚拟方法。所以对于这个问题,让 prentend GetAsyncPostAsync方法是虚拟的......请:)

5 个答案:

答案 0 :(得分:12)

这是我的(或多或少)通用FakeHttpMessageHandler。

public class FakeHttpMessageHandler : HttpMessageHandler
{
    private HttpResponseMessage _response;

    public static HttpMessageHandler GetHttpMessageHandler( string content, HttpStatusCode httpStatusCode )
    {
        var memStream = new MemoryStream();

        var sw = new StreamWriter( memStream );
        sw.Write( content );
        sw.Flush();
        memStream.Position = 0;

        var httpContent = new StreamContent( memStream );

        var response = new HttpResponseMessage()
        {
            StatusCode = httpStatusCode,
            Content = httpContent
        };

        var messageHandler = new FakeHttpMessageHandler( response );

        return messageHandler;
    }

    public FakeHttpMessageHandler( HttpResponseMessage response )
    {
        _response = response;
    }

    protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken )
    {
        var tcs = new TaskCompletionSource<HttpResponseMessage>();

        tcs.SetResult( _response );

        return tcs.Task;
    }
}

以下是我的一个测试中使用它的一个示例,它希望将一些JSON作为返回值。

const string json = "{\"success\": true}";

var messageHandler = FakeHttpMessageHandler.GetHttpMessageHandler( 
    json, HttpStatusCode.BadRequest );
var httpClient = new HttpClient( messageHandler );

您现在可以将httpClient注入您正在测试的类中(使用您喜欢的任何注入机制),并且在调用GetAsync时,您的messageHandler会将您告诉它的结果吐回。

答案 1 :(得分:3)

当我需要与Gravatar服务进行交互时,我做了类似的事情。我试图使用假货/模拟,但发现用HttpClient是不可能的。相反,我提出了一个自定义的HttpMessageHandler类,它允许我按照这些方式预加载预期的响应:

using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Tigra.Gravatar.LogFetcher.Specifications
    {
    /// <summary>
    ///   Class LoggingHttpMessageHandler.
    ///   Provides a fake HttpMessageHandler that can be injected into HttpClient.
    ///   The class requires a ready-made response message to be passed in the constructor,
    ///   which is simply returned when requested. Additionally, the web request is logged in the
    ///   RequestMessage property for later examination.
    /// </summary>
    public class LoggingHttpMessageHandler : DelegatingHandler
        {
        internal HttpResponseMessage ResponseMessage { get; private set; }
        internal HttpRequestMessage RequestMessage { get; private set; }

        public LoggingHttpMessageHandler(HttpResponseMessage responseMessage)
            {
            ResponseMessage = responseMessage;
            }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
            {
            RequestMessage = request;
            return Task.FromResult(ResponseMessage);
            }
        }
    }

然后我的测试上下文设置如下:

public class with_fake_gravatar_web_service
    {
    Establish context = () =>
        {
        MessageHandler = new LoggingHttpMessageHandler(new HttpResponseMessage(HttpStatusCode.OK));
        GravatarClient = new HttpClient(MessageHandler);
        Filesystem = A.Fake<FakeFileSystemWrapper>();
        Fetcher = new GravatarFetcher(Committers, GravatarClient, Filesystem);
        };

    protected static LoggingHttpMessageHandler MessageHandler;
    protected static HttpClient GravatarClient;
    protected static FakeFileSystemWrapper Filesystem;
    }

然后,这是一个使用它的测试(规范)的例子:

[Subject(typeof(GravatarFetcher), "Web service")]
public class when_fetching_imagaes_from_gravatar_web_service : with_fake_gravatar_web_service
    {
    Because of = () =>
        {
        var result = Fetcher.FetchGravatars(@"c:\"); // This makes the web request
        Task.WaitAll(result.ToArray());
        //"http://www.gravatar.com/avatar/".md5_hex(lc $email)."?d=404&size=".$size; 
        UriPath = MessageHandler.RequestMessage.RequestUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
        };

    It should_make_request_from_gravatar_dot_com =
        () => MessageHandler.RequestMessage.RequestUri.Host.ShouldEqual("www.gravatar.com");

    It should_make_a_get_request = () => MessageHandler.RequestMessage.Method.ShouldEqual(HttpMethod.Get);
    // see https://en.gravatar.com/site/check/tim@tigranetworks.co.uk
    It should_request_the_gravatar_hash_for_tim_long =
        () => UriPath.ShouldStartWith("avatar/df0478426c0e47cc5e557d5391e5255d");

    static string UriPath;
    }

您可以在http://stash.teamserver.tigranetworks.co.uk/users/timlong/repos/tigra.gravatar.logfetcher/browse

看到完整的来源

答案 2 :(得分:2)

与大多数模拟库一样,FakeItEasy不会为非抽象组件创建代理。对于HttpClientGetAsyncPostAsync方法既不是virtual也不是abstract,因此您无法直接创建它们的存根实现。请参阅https://github.com/FakeItEasy/FakeItEasy/wiki/What-can-be-faked

在这种情况下,您需要一个不同的抽象作为依赖项 - HttpClient可以实现的一个,但其他实现也可以实现,包括模拟/存根。

答案 3 :(得分:1)

您还可以创建一个AbstractHanler,可以在其上截取公共抽象方法。例如:

public abstract class AbstractHandler : HttpClientHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(SendAsync(request.Method, request.RequestUri.AbsoluteUri));
    }

    public abstract HttpResponseMessage SendAsync(HttpMethod method, string url);
}

然后,您可以像这样拦截对AbstractHandler.SendAsync(HttpMethod method, string url)的呼叫:

// Arrange
var httpMessageHandler = A.Fake<AbstractHandler>(options => options.CallsBaseMethods());
A.CallTo(() => httpMessageHandler.SendAsync(A<HttpMethod>._, A<string>._)).Returns(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Result")});
var httpClient = new HttpClient(httpMessageHandler);

// Act
var result = await httpClient.GetAsync("https://google.com/");

// Assert
Assert.Equal("Result", await result.Content.ReadAsStringAsync());
A.CallTo(() => httpMessageHandler.SendAsync(A<HttpMethod>._, "https://google.com/")).MustHaveHappenedOnceExactly();

有关更多信息,请参见以下博客:https://www.meziantou.net/mocking-an-httpclient-using-an-httpclienthandler.htm

答案 4 :(得分:0)

这不是直接回答你的问题,但是我不久前写了一个库,它提供了一个用于截断请求/响应的API。它非常灵活,支持有序/无序匹配以及可定制的回退系统,可以提供无与伦比的请求。

可在GitHub上找到:https://github.com/richardszalay/mockhttp