4

I'm using a wrapper for HttpClient to be able to emulate http responses. I'm having a problem with those who are sending anonymous types.

This is the setup response for my HttpClient class wrapper:

 var x = new {category = 1, products = "1"};

 Func<HttpRequestMessage, HttpResponseMessage> functionResponse;
 functionResponse = request => 
                   request.CreateResponse(code, responseValue, _httpConfig);

 _client.PostAsJsonAsync(
           Arg.Is<string>(x => x.Contains(URL)), 
           Arg.Is<T>(x => x.ToJsonStringSafe() == postValue.ToJsonStringSafe())
         ).Returns(
          System.Threading.Tasks.Task.Factory.StartNew(() => 
            functionResponse(_message)));

This is piece of code in the target method doing the httpClient call:

    var response =

            await _httpClient.PostAsJsonAsync(
                                        _serviceUrl + "/productbyid", 
                                        new {category = _category, products = _products});

At this point, response is null, but should be a Task with responseValue set.

This configuration is working for anything but anonymous types.

*I verified the match of URL, category and _products on debug time.

celerno
  • 1,367
  • 11
  • 30
  • Not totally related to your question, but take a look at https://github.com/richardszalay/mockhttp. It'll probably make your life easier. Has made mine. – Michael Benford Apr 11 '15 at 03:08
  • @MichaelBenford Hi there, thank you. instead of that I've created a wrapper class, and passing httpclient with dependancy injection pattern. – celerno Apr 13 '15 at 14:28
  • 1
    Did you ever get to mock this as where I am working at moment has very similar situation and am trying to put some tests, using NSubstitute, around a service with calls postasjsonasync just as you have above? – CheGuevarasBeret Jun 22 '16 at 13:39
  • Hi. Never for anonymous types. I had to create one for each type I was expecting. At the end, that amount of code make sense regarding unit testing principles and It wasn't a big problem tho. – celerno Jun 23 '16 at 18:02

0 Answers0