maxkagamine / moq.contrib.httpclient Goto Github PK
View Code? Open in Web Editor NEWA set of extension methods for mocking HttpClient and IHttpClientFactory with Moq.
License: MIT License
A set of extension methods for mocking HttpClient and IHttpClientFactory with Moq.
License: MIT License
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");
}
Heya!
An HttpClient
can throw an exception, under certain circumstances. Is there a way to do that with this library?
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.
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.
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:
Actual behavior:
Workaround:
(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)
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.
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.
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!
Question: In the handler.VerifyRequest portion of a test ...is there a way to log out what the url and response was that was monitored? Like, expected http://uri, received, http://uri2?
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.