Git Product home page Git Product logo

moq.contrib.httpclient's People

Contributors

maxkagamine avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

moq.contrib.httpclient's Issues

Unsupported expression: x => x.CreateClient() Extension methods (here: HttpClientFactoryExtensions.CreateClient) may not be used in setup / verification expressions.

The following code:

Mock<HttpMessageHandler> handler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
IHttpClientFactory factory = handler.CreateClientFactory();

// Named clients can be configured as well (overriding the default)
Mock.Get(factory).Setup(x => x.CreateClient())
         .Returns(() =>
         {
                HttpClient client = handler.CreateClient();
                client.BaseAddress = new Uri("https://example.com");
                return client;
         });

Throwing the following error:

System.NotSupportedException : Unsupported expression: x => x.CreateClient()
Extension methods (here: HttpClientFactoryExtensions.CreateClient) may not be used in setup / verification expressions.

Note: I am trying to mock following code:

 private readonly HttpClient _skrillHttpClient;
 public SkrillService(IHttpClientFactory httpClientFactory)
 {
     _skrillHttpClient = httpClientFactory.CreateClient();
    _skrillHttpClient.BaseAddress = new Uri("https://www.skrill.com");
 }

Dotnet 7: The value cannot be null or empty. (Parameter 'mediaType')

In dotnet 7 if you do not set the mediaType, and allow the default null value to be used, then an exception will be thrown:

ArgumentException: "The value cannot be null or empty. (Parameter 'mediaType')"
at System.Net.Http.Headers.MediaTypeHeaderValue.CheckMediaTypeFormat(String mediaType, String parameterName)
at System.Net.Http.StringContent..ctor(String content, Encoding encoding, String mediaType)
...

I looked into this and StringContent has been changed. For the constructor that takes a mediaType string as the third parameter a null value will no longer be translated into the constant DefaultMediaType which is "text/plain". Consequently, when MediaTypeHeaderValue. CheckMediaTypeFormat() is called an ArgumentException will result.

dotnet/runtime@f132942

It looks to me like this could be fixed by updating RequestExtension.cs. The various ReturnsResponse methods that have a mediaType parameter with a default of null could change the default to "text/plain". Or the lines of code that directly create a StringContent could use the null-coalescing operator to return "text/plain" when mediaType is null.

Repeated calls to SetupRequest only returns reponse once, then fails

Hi,

Nice library! I am not a fan of extension methods but in this case didn't want to wrap the httpclient and factory stuff in an own interface, and this was a nice and quick solution.

We ran into one unexpected behaviour that seems inconsistent with Moq

Expected behavior:

  • repeated calls to SetupRequest keep returning the same response (you can verify how often the call is done with Times ...)

Actual behavior:

  • the first call after SetupRequest returns the response, but the second call doesn't return anything

Workaround:

  • we used SetupRequestSequence to return the same response twice.

(If I have time later I'd be willing to see if I could fix this myself with a unit test - looking at the tests helped me guess where the issue is, as I couldn't find a test setup for this scenario)

Use in TestServer

Como lo uso con TestServer para simular

services.AddHttpClient(NamesEndPointConstants.DatosBasicos, config =>
            {
                config.BaseAddress = new Uri(configuration.GetUrlDatosBasicos());
            }).SetHandlerLifetime(TimeSpan.FromMinutes(5))
              .AddPolicyHandler(GetRetryPolicy());

por ejemplo.

Compiler warning CS8002: Referenced assembly does not have a strong name

I'm using Moq.Contrib.HttpClient in a .NET 8 unit test project where my assemblies need to be strong-named. I'm getting a warning referencing Moq.Contrib.HttpClient:

Warning CS8002 Referenced assembly 'Moq.Contrib.HttpClient, Version=1.4.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name.

All of the other assemblies I use for unit testing are strong-named and it'd be nice to see this package add a strong-name :) . I realize I can strong-name it myself but I think that is rather hacky.

Method for validating request Content

Is there a way to assert on the content of the request?

I want to validate that an external library using the mocked client is sending the correct info to the endpoint.

Thanks!

Issues with 'ReturnsJsonResponse' and Deserializing the Response-Content

If a Https calls Content.ReadAsStreamAsync() to get the Content and deserialize that Value, the returned object only contains null-values.

I created a Unit Test for this Issue:

  ```
  [Fact]
  public async Task RespondsWithJson_NoExtension()
  {
      // Once again using our music API from MatchesCustomPredicate, this time fetching songs
      var expected = new List<Song>()
      {
          new Song()
          {
              Title = "Lost One's Weeping",
              Artist = "Neru feat. Kagamine Rin",
              Album = "世界征服",
              Url = "https://youtu.be/mF4KTG4c-Ic"
          },
          new Song()
          {
              Title = "Gimme×Gimme",
              Artist = "八王子P, Giga feat. Hatsune Miku, Kagamine Rin",
              Album = "Hatsune Miku Magical Mirai 2020",
              Url = "https://youtu.be/IfEAtKW2qSI"
          }
      };

      handler.SetupRequest(HttpMethod.Get, "https://example.com/api/songs").ReturnsJsonResponse(expected);

      // Following line works as expected
      // handler.SetupRequest(HttpMethod.Get, "https://example.com/api/songs").ReturnsJsonResponse(expected, new JsonSerializerOptions());
      
      var actualMessage = await client.GetAsync("api/songs");
      var actualBody = await actualMessage.Content.ReadAsStreamAsync();
      var actual = await JsonSerializer.DeserializeAsync<List<Song>>(actualBody);
      
      actual.Should().BeEquivalentTo(expected);
  }

```

If I call .ReturnsJsonResponse(HttpStatusCode.OK, expectedResponse, new JsonSerializerOptions()); and provide any JsonSerializerOptions, the tests works s expected.

I'm not sure, if this is an actual error or a misleading documentation or ReturnsJsonResponse

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.