Giter Site home page Giter Site logo

mockhttp's People

Contributors

coryflucas avatar esskar avatar jericho avatar jozefizso avatar jr01 avatar nicolaiarocci avatar perfectsquircle avatar richardszalay avatar wislon 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mockhttp's Issues

Headers in the response

I there a way to specify headers in the response of a mocked request?

This is how I am currently mocking the response and specifying the content of the response but I can't figure out how to specify the headers

var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "https://api.myvendor.com/v1/myendpoint")
	.With(request => request.Content == null)
	.Respond("application/json", "{'name' : 'This is a test'}");

The reason I'm asking is because the API is returning information in the header regarding throttling (such as how many calls I have left in the next X seconds, how long I should wait until my next call if I exceed max calls per second, etc.) and I want to unit test my code which handles these header items.

Fails to read response content twice

public class MockHttpMessageHandlerTests
{
    //this test is OK and copied from tests in this repo
    [Fact]
    public void Should_respond_with_basic_requests()
    {
        var mockHandler = new MockHttpMessageHandler();

        mockHandler
            .When("/test")
            .Respond("application/json", "{'Status' : 'OK'}");

        var httpClient = new HttpClient(mockHandler);
        var result = httpClient.GetAsync("http://invalid/test").Result;

        Assert.Equal(System.Net.HttpStatusCode.OK, result.StatusCode);
        Assert.Equal("application/json", result.Content.Headers.ContentType.MediaType);
        var responseDto = result.Content.ReadAsAsync<ResponseDto>().Result;
        Assert.Equal("OK", responseDto.Status);
    }

    //this test fails
    [Fact]
    public void Should_respond_with_basic_requests_2()
    {
        var mockHandler = new MockHttpMessageHandler();

        mockHandler
            .When("/test")
            .Respond("application/json", "{'Status' : 'OK'}");

        var httpClient = new HttpClient(mockHandler);
        var result = httpClient.GetAsync("http://invalid/test").Result;

        Assert.Equal(System.Net.HttpStatusCode.OK, result.StatusCode);
        Assert.Equal("application/json", result.Content.Headers.ContentType.MediaType);
        var responseDto = result.Content.ReadAsAsync<ResponseDto>().Result;
        Assert.Equal("OK", responseDto.Status);

        result = httpClient.GetAsync("http://invalid/test").Result;
        Assert.Equal(System.Net.HttpStatusCode.OK, result.StatusCode);
        Assert.Equal("application/json", result.Content.Headers.ContentType.MediaType);
        responseDto = result.Content.ReadAsAsync<ResponseDto>().Result;

        //this fails due to responseDto is null. 
        Assert.Equal("OK", responseDto.Status);
    }
}

public class ResponseDto
{
    public string Status { get; set; }
}

Remove dependency of Install-Package System.Net.Http nuget package

I have a project with a reference to System.Net.Http library. [From .NET assemblies, not the nuget package]

When I install the RichardSzalay.MockHttp package it installs also the System.Net.Http nuget package.
There is any way to remove this dependency?

[Sorry for my bad English]

System.NullReferenceException trying to return a null response

Trying to test the case when httpClient returns null:

var mockHttp = new MockHttpMessageHandler();
mockHttp.Fallback.Respond(() => Task.FromResult<HttpResponseMessage>(null));
var r = mockHttp.ToHttpClient().GetAsync("http://a").Result;

...throws a null reference exception.

Simulate delay or timeout?

How can I simulate a network delay, or a timeout (where the response never arrives)?

I tried this but it doesn't work:

 client.Timeout = 1;
 mock.When("*").Respond(async () => { await Task.Delay(1000); return null; } );

HttpClient and HttpResponseHandler "Respond" extensions don't actually work properly

c70bf4f

Your tests directly invoke the "SendAsync" method of your custom handler, thus they pass; however, utilizing your custom handler within an HttpClient and attempting to pass the request to a different HttpClient/Handler will fail with the following error:

The request message was already sent. Cannot send the same request message multiple times.

Am I not understanding the correct usage of these extension methods or is this an accidental oversight?

If HttpResponseMessage is disposed next request fails

It would be nice to have an option to make it return a new HttpResponseMessage on every call.
I have a code that disposes the message after extracting the contents and unit tests broke because the response instance gets disposed inside the mock.

System.ObjectDisposedException occurred
Message: Exception thrown: 'System.ObjectDisposedException' in System.Net.Http.dll
Additional information: Cannot access a disposed object.

Add support for Windows.Web.Http.HttpClient

When writing native for the UWP platform, Windows.Web.Http.HttpClient has some performance benefits due to it's native implementation. It might be worth supporting an alternate MockHttpClient class that works with those types instead.

Remove Profile111

According to ".NET Standard Library - PCL Compatibility", netstandard1.1 is compatible with Profile111.

That being the case, it should be fine to remove Profile111 from the build. The only thing I can see being an issue is it would be dropping support for NuGet 2.x (since it doesn't support the netstandard TFMs)

How to figure out the the URL when 'No matching mock handler' exception occurs?

I'm getting a No matching mock handler in my unit test which is most likely caused by a typo in my expectation:

var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "...the url...").Respond("application/json", "...the response...");

but I can't figure out what I typed wrong. Is there any way to get the actual URL?

Throw System.MissingMethodException when call ToHttpClient

Hi,

I have an exception throw when I try to call MockHttpMessageHandler::ToHttpClient.

So my code is very simple, and a really don't understand where this problem come from.
Do you have any idea about that ?

Thanks in advance pour your help ;)

The Exception:

System.MissingMethodException: Method not found : 'System.Net.Http.HttpClient RichardSzalay.MockHttp.MockHttpMessageHandler.ToHttpClient()'.

The code which produce the exception

using RichardSzalay.MockHttp;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AllTest
{
    [TestClass]
    public class MyClassTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            (new MockHttpMessageHandler()).ToHttpClient();
        }
    }
}

Version info:

  • Target: Net4.6.1
  • Visual Studio 15.7.4
  • .Net Framework: 4.7.02558

package.config

<packages>
  <package id="Castle.Core" version="4.3.1" targetFramework="net461" />
  <package id="Moq" version="4.8.3" targetFramework="net461" />
  <package id="MSTest.TestAdapter" version="1.3.2" targetFramework="net461" />
  <package id="MSTest.TestFramework" version="1.3.2" targetFramework="net461" />
  <package id="Newtonsoft.Json" version="11.0.2" targetFramework="net461" />
  <package id="RichardSzalay.MockHttp" version="5.0.0" targetFramework="net461" />
  <package id="SimpleInjector" version="4.3.0" targetFramework="net461" />
  <package id="System.IO.Abstractions" version="2.1.0.199" targetFramework="net461" />
  <package id="System.IO.Abstractions.TestingHelpers" version="2.1.0.199" targetFramework="net461" />
  <package id="System.Net.Http" version="4.3.3" targetFramework="net461" />
  <package id="System.Runtime.CompilerServices.Unsafe" version="4.5.1" targetFramework="net461" />
  <package id="System.Security.Cryptography.Algorithms" version="4.3.1" targetFramework="net461" />
  <package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net461" />
  <package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net461" />
  <package id="System.Security.Cryptography.X509Certificates" version="4.3.2" targetFramework="net461" />
  <package id="System.Threading.Tasks.Extensions" version="4.5.1" targetFramework="net461" />
  <package id="System.ValueTuple" version="4.5.0" targetFramework="net461" />
</packages>

Relative URLs always fail to match on Xamarin Android

var handler = new MockHttpMessageHandler();
handler.When("/local").Respond(HttpStatusCode.OK);

var client = new HttpClient(handler);
var result = client.GetAsync("http://localhost/local").Result;
result.EnsureSuccessStatusCode();

Check that no request was sent

As far as I understand it, I can use the MockHttpHandler to set up expectations that have to be met by my system under test, like "My SUT should make a call to this URL". Is there a way to check that no request was made at all?

Add strong name to assembly

Could you add a strong name to the MockHttp assembly, so it can be referenced from unit testing projects that are strongly named?

Add support for .NET Core

Since HttpClient is supported by aspnercore, it makes sense for mockhttp to work in that environment.

When reading request body MockHttp throws exception

An exception is thrown when using an Expect with WithFormData throws a null object exception when reading the results from ReadToStringAsync. This is with ASP.Net Core 1.1.0 running on the 4.6.1 framework.

.Net 461

Hi RIchard,

I'm trying to use MockHttp in a .Net 4.6.1 project and I'm hitting an issue where there seems to be a clash of System.Net.http packages. I end up with one of two issues, either I can't install MockHttp as there is a clash with the version of System.Net.Http in the GAC, or I install both System.Net.Http and MockHttp from NuGet, run the test and get this:

[A]System.Net.Http.Headers.MeadiaTypeHeaderValue cannot be cast to [B]System.Net.Http.Headers.MeadiaTypeHeaderValue, which I guess means that it's trying to use two different versions of System.Net.Http.

I wondered if you'd seen this and if there's an easy fix?

Thanks

Support more targets

Per our email conversation, here is the profile we are using:

Profile328

Thank you in advance.

question can or cannot I mock up two api calls

I try to mock up two api calls :

https://www.rijksmuseum.nl/api/nl/collection/SK-C-1368?key=fakekey&format=json
https://www.rijksmuseum.nl/api/nl/collection/SK-C-1368/tiles?key=fakekey&format=json

I did in my code this :

mockHttp.When("https://www.rijksmuseum.nl/api/nl/collection/SK-C-1368/t*")
            .Respond("application/json", File.ReadAllText("image.json"));

        mockHttp.When("https://www.rijksmuseum.nl/api/nl/collection/SK-C-1368?k*")
            .Respond("application/json", File.ReadAllText("data.json")); 

but still I see the tests failing with this error message :

Message: System.Net.Http.HttpRequestException : Response status code does not indicate success: 404 (No matching mock handler).

so can I mock up these two calls with your library or did I do something else wrong ?

FormDataMatcher does not decode + into space correctly

When using MockHttpMessageHandler.WithFormData() to match form data that use spaces, matching does not work correctly because + sign in the data is not unescaped correctly to space.

var data = new Dictionary<string, string>() { {"param", "Parameter with space" } };
var dataForHttpClient = new FormUrlEncodedContent(data);

// query string produced by FormUrlEncodedContent.Encode():
// param=Parameter+with+space

var httpMock = new MockHttpMessageHandler();
httpMock.Expect(HttpMethod.Post, "https://server.org/api/command")
.WithFormData(data);

// will throw exception because FormDataMatcher will not convert + to back to space
httpMock.VerifyNoOutstandingExpectation();
// FormUrlEncodedContent from HttpClient library
public class FormUrlEncodedContent : ByteArrayContent
{
    private static string Encode(string data)
    {
      if (string.IsNullOrEmpty(data))
        return string.Empty;
      return Uri.EscapeDataString(data).Replace("%20", "+");
    }
}

FormDataMatcher is using QueryStringMatcher.ParseQueryString() to decode posted data. That method uses only Uri.UnescapeDataString() which does not follow URL spec and does not convert + back to space.

More info on URLs and URIs in .NET: Don't use .NET System.Uri.UnescapeDataString in URL Decoding

System.TypeLoadException when mocking response with status code other than 2xx

I have the following test setup:

var mockHttp = new MockHttpMessageHandler();

mockHttp.Expect("/oauth/token/")
      .Respond(HttpStatusCode.OK, "application/json", "{'ok':true}");

This works fine, but when I set the response status code to HttpStatusCode.Unauthorized (for example), I get the following error:

System.TypeLoadException : Could not resolve type with token 01000090 (from typeref, class/assembly System.Net.HttpStatusDescription, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)

I wonder if it might have something to do with the warning I get when using this library:

Warning: Assuming assembly reference 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f711d50a3a' used by 'RichardSzlalay.MockHttp' matches identity 'System.Net.Http, Version=4.1.1.1, Culture=neutral, PublicKeyToken=b03f5f711d50a3a' of 'System.Net.Http', you may need to supply runtime policy

Our REST-library is refit and I use the mock like:

var refitSettings = new RefitSettings {
       HttpMessageHandlerFactory = mockHttp
};

RestService.For<IBackendAPI>(baseURL, refitSettings);

Case Insensitive URLs

Steps to Reproduce:

  1. Call mockHttpMessageHandler.Expect(url).Respond(object) with a url that contains capital letters and where object is of type T.
  2. Continue a test that calls a method which uses an HttpClient with the supplied mockHttpMessageHandler. This method internally creates a Uri object from the same url string (with capital letters). This in essence makes all letters lowercase.

Expected result: http call returns successful response and response.Content.ReadAsAsync<T>() returns "object".

Actual result: http call returns successful response, but response.Content.ReadAsAsync<T>() returns "object" throws an exception:

"System.ArgumentNullException

: Value cannot be null.
Parameter name: content"

Workaround: make "url" all lowercase.

Retrying the exact same request

Is there a way to mock a situation where the exact same request is made twice but the response is different? The scenario is that my class has automatic retry in certain cases and I want to unit test the 'retry' code. I wrote the following unit test but the second mock is never used, only the first one which causes the Assert.IsTrue to fail.

// Arrange
var mockHttp = new MockHttpMessageHandler();

// First attempt, we return HTTP 429 which means TOO MANY REQUESTS
mockHttp.When(HttpMethod.Get, "https://my.api.com/myendpoint")
	.With(request => request.Content == null)
	.Respond((HttpStatusCode)429);

// Second attempt, we return the expected result
mockHttp.When(HttpMethod.Get, "https://my.api.com/myendpoint")
	.With(request => request.Content == null)
	.Respond("application/json", "{'name' : 'This is a test'}");

var httpClient = new HttpClient(mockHttp);
var client = new MyClient(httpClient);

// Act
var result = client.GetAsync("myendpoint", CancellationToken.None).Result;

// Assert
mockHttp.VerifyNoOutstandingExpectation();
mockHttp.VerifyNoOutstandingRequest();
Assert.IsTrue(result.IsSuccessStatusCode);

By the way, I was a little bit surprised to notice that VerifyNoOutstandingExpectation does not fail despite the fact that only one of my two mocks is invoked.

System.BadImageFormatException : Method has zero rva

at RichardSzalay.MockHttp.MockHttpMessageHandler..ctor () [0x00021] in <0d860c8b76844946b74639bb21eec72f>:0 at TestClass.Setup () [0x00012] in TestClass.cs:25 at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in /private/tmp/source-mono-4.6.0/bockbuild-xamarin/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/corlib/System.Reflection/MonoMethod.cs:309

` private MockHttpMessageHandler mockHttp;
private CheckoutClient checkoutOrderClient;

    [SetUp]
    public void Setup()
    {
        this.checkoutOrderClient = new CheckoutClient("https://localhost");
        this.mockHttp = new MockHttpMessageHandler();

        FlurlHttp.Configure(c => {
            c.OnErrorAsync = RestExceptionHandler.HandleException;
            c.HttpClientFactory = new MockHttpFactory(mockHttp);
        });
    }

`

this is line 25 this.mockHttp = new MockHttpMessageHandler();

Do you know what I am doing wrong?

Problem with multiple requests

Hi Richard,
I generally like your library but I am currently experiencing a problem.
If I call your mockHttpHandler twice the second time always responds with NotFound

For example this test does not pass

var mockHttp = new MockHttpMessageHandler();

mockHttp.Expect("http://someurl/api/stuff")
.WithHeaders("authorization", "Bearer bad-token")
.Respond(HttpStatusCode.Unauthorized);

var httpClient = new HttpClient(mockHttp) {BaseAddress = new Uri("http://someurl")};
var message = new HttpRequestMessage(HttpMethod.Get, $"/api/stuff");
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "bad-token");
var response = await httpClient.SendJsonAsync<ApiMultipleResponse<GetSampleTypesResponse>>(message);

//assert
Assert.NotNull(response);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);

message = new HttpRequestMessage(HttpMethod.Get, $"/api/stuff");
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "bad-token");
response = await httpClient.SendJsonAsync<ApiMultipleResponse<GetSampleTypesResponse>>(message);

//assert
Assert.NotNull(response);
// This assert will fail as response.StatusCode is HttpStatusCode.NotFound
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);

Support for "AnyTime-When"

Would you be opposed to adding support for defining loose "Whens" that can occur at any point during a test, not just after all the expects are complete? There are some perpetually occurring HTTP requests that can occur in the background during tests (depending on the service) that are non deterministic. It'd be nice if we could prepare for these cases.

Sign the assembly in the nuget.org package?

Hi,

Would it be possible to sign the assemblies in the RichardSzalay.MockHttp package on nuget.org?

This would make it easier for more people to use, in case their build & test pipelines require strong-named assemblies.

There's a MockHttpSigned package on nuget.org, however the origin of that package is a little unclear and it hasn't been updated since MockHttp 1.2.1 (in 2015).

Thanks,

Andrew Huff

Simulate httpClient Throwing an Exception (Feature Request)

Add support to mock an httpClient throwing an exception. Usage might be something like:

 _mockHttpMessageHandler.Expect(urlBase)
     .WithQueryString(string.Format(queryString, id))
     .ThrowsException(new Exception("HTTP call threw an exception."));

Align with HttpClient multi-targeting recommendations

Based on: https://leastprivilege.com/2018/05/21/the-state-of-httpclient-and-net-multi-targeting/

Will require the following changes:

  • Add a .NetStandard2.0 target that only references NETStandard.Library
  • Update the .NETFramework4.5 target so that it has a frameworkAssembly rather than a dependency

The rest of the targets can remain as-is for compatibility, but since this will change the behavior for netfx45 we'll need to release it as a major/breaking version.

RequestMessage is not set on HttpResponseMessage

In the process of testing some code, I received some confusing null reference exceptions in code paths that were known to work without the mocking. It turns out this was because mockhttp does not set the RequestMessage on HttpResponseMessage.

Content is not disposed when request is dispatched

I have a bug in my code because I attempt to issue the same HttpRequestMessage twice and I want to write a unit test to demonstrate the issue and to show that the code I am about to write indeed solves the issue.

I wrote the following unit test to demonstrate the underlying problem:

[Test]
public void Retry_httpClient()
{
    var mockHttp = new MockHttpMessageHandler();

    mockHttp.Expect(HttpMethod.Post, "https://api.fictitious-vendor.com/v1/endpoint").Respond("application/json", "{'name' : 'This is a test'}");
    mockHttp.Expect(HttpMethod.Post, "https://api.fictitious-vendor.com/v1/endpoint").Respond("application/json", "{'name' : 'This is a test'}");

    var request = new HttpRequestMessage(HttpMethod.Post, "https://api.fictitious-vendor.com/v1/endpoint")
    {
        Content = new StringContent("Hello World!")
    };

    var httpClient = mockHttp.ToHttpClient();
    httpClient.SendAsync(request);
    httpClient.SendAsync(request);
}

This unit test fails when it attempts to dispatch the request for the second time with a The request message was already sent. Cannot send the same request message multiple times. exception. This is excellent: the unit test reproduces the issue my code is experiencing.

My next step is to write a fix for this issue by 'cloning' the request before each attempt. Something like this:

[Test]
public void Retry_httpClient()
{
    var mockHttp = new MockHttpMessageHandler();

    mockHttp.Expect(HttpMethod.Post, "https://api.fictitious-vendor.com/v1/endpoint").Respond("application/json", "{'name' : 'This is a test'}");
    mockHttp.Expect(HttpMethod.Post, "https://api.fictitious-vendor.com/v1/endpoint").Respond("application/json", "{'name' : 'This is a test'}");

    var request = new HttpRequestMessage(HttpMethod.Post, "https://api.fictitious-vendor.com/v1/endpoint")
    {
        Content = new StringContent("Hello World!")
    };

    var httpClient = mockHttp.ToHttpClient();
    httpClient.SendAsync(Clone(request));
    httpClient.SendAsync(Clone(request));
}

public static HttpRequestMessage Clone(HttpRequestMessage request)
{
    HttpRequestMessage clone = new HttpRequestMessage(request.Method, request.RequestUri)
    {
        Content = request.Content,
        Version = request.Version
    };

    foreach (var prop in request.Properties)
        clone.Properties.Add(prop);
    foreach (var header in request.Headers)
        clone.Headers.TryAddWithoutValidation(header.Key, header.Value);

    return clone;
}

This unit test completed successfully which led me to believe I had solved the issue but when I tried against an actual HTTP server instead of using mockHttp, I received an exception that said I was accessing a disposed object. It took me a while to figure out that the 'object' in question was the content of the request and the root of the issue is that HttpClient disposes the content stream after the request is dispatched and therefore no longer available for the second request.

I was able to fix this problem by cloning the content as well as the request, but my question is: why is it that I didn't get the same exception when running the unit test utilizing mockHttp?

I'm guessing there's a slight difference between how MockHttp and the 'real' HttpClient handle the content when a request is dispatched?

Update build system

The current build system has a number of issues:

  1. It uses the old approach of having one project per target
  2. The NetStandard project uses project.json, which requires the preview tooling for .NET Core

This was somewhat workable while I had VS2015 and the preview tooling installed, but now I only have VS2017.3 so an update has become necessary to release new versions.

Ideally:

  1. The build will have a single library project that has TargetPlatforms set for all the current TFMs. I'm not sure if PCLs are supported, so this may have to end up as two.
  2. If the build becomes a single project, it should generate a nupkg using the new csproj-based system.
  3. It should ideally build on .NET Core (inc. Linux/macOS), automatically dropping the Windows-only TFMs

Support for verifying a request was made

Firstly, this is a great library 👍

It would be great to have a verify method somewhat like that in Moq. So that I can verify that my HttpClient made was called at all with the correct URL, regardless of response. Could also include functionality for expecting a particular response.

e.g.

new MockHttpMessageHandler().VerifyUrlFetched("some url", Times.Once);

Is this something you would consider adding to the API?

Missing AssemblyVersionInfo.cs causes NetStandard project build to fail

I'm guessing you have some process that generates this file during the build on AppVeyor which ensures the project builds successfully but this doesn't work when we work with your source locally since the file doesn't exist. Other projects are fine because they include this file only if it exists.

Could not load file or assembly

i got the issue as follows:-
Could not load file or assembly 'RichardSzalay.MockHttp, Version=1.3.1.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The bound assembly has a version that is lower than that of the request. (Exception from HRESULT: 0x80132000).

when i was working for windows phone it worked absolutely fine.
but when i was replicating the same functionality for windows 8, i got the above error.
can you please help me out on this.
thanks

Nuget Version issue in Visual Studio 2013

When installing the package RichardSzalay.MockHttp in a project using Visual Studio 2013's NuGet Package Manager, it throws the following error:

Attempting to resolve dependency 'System.Net.Http (≥ 4.0.0)'.
The 'System.Net.Http 4.0.0' package requires NuGet client version '3.0' or above, but the current 
NuGet version is '2.12.0.817'.

When I try to upgrade NuGet client, I don't find any update in the Visual Studio Gallery! Even the latest version is 2.12.xx on NuGet Official Page for VS 2013.

Am I missing something?

Project can't build on Mac OS due to NuGet outdated

When using Mac OS to build projects targeting .NET 4.5, you have a dependency on System.Net.Http version 4.0, this causes a problem since this package depends on NuGet version 3, which is not available yet on Xamarin Studio stable channel (will be supported in 6.1, but it is still very early on preview), so you just can't build a project referencing MockHttp.

This is the error I get:
2016-07-11T22:22:05.800Z: The 'System.Net.Http 4.0.0' package requires NuGet client version '3.0' or above, but the current NuGet version is '2.8.5.0'.

Could .NET 4.5 also depend on Microsoft.Net.Http instead of System.Net.Http? Or is there any workaround for this?

Add some more fluent APIs

Currently, creating a mock HttpClient looks like this:

var mockHandler = new MockHttpMessageHandler();
mockHandler.When("urAl").Respond(responseA);
mockHandler.When("urlA").Respond(responseB);
var httpClient = new HttpClient(mockHandler);

This could be made cleaner, at least for single-url mocks, via an AsHttpClient() method:

var httpClient = new MockHttpMessageHandler()
    .When("urlA").Respond(responseA)
    .AsHttpClient();

This could be taken one step further by having Respond return the MockHttpMessageHandler, allowing the following:

var httpClient = new MockHttpMessageHandler()
    .When("urlA").Respond(responseA)
    .When("urlB").Respond(responseB)
    .AsHttpClient();

It would even work for complex requirements with some imaginative spacing:

var httpClient = new MockHttpMessageHandler()
    .When("urlA")
        .WithQueryString("key", "value")
        .Respond(responseA)
    .When("urlB")
        .Respond(responseB)
    .AsHttpClient();

It's important that these changes be made in a backward-compatible fashion.

Bump major version to 3.x

There is a bug in the latest version of NuGet (that shipped with .NET Core 2) that causes the "unlisted" property to be ignored on the highest version of a package when no version is specified. This is causing mockhttp 3.0 (published in error of version 1.3) to be installed at an increasingly large scale.

The NuGet bug has been marked with Priority:1, but I don't think mockhttp should wait for it to be fixed. Instead, version 1.5.1 will be released as 3.1 with this issue being the only resolved change.

Respond to exact url with querystring

Hi

How can I make sure to only respond when the exact url with querystring is called.
Given these variations, the response is always given.

_mockHttpHandler
       .When($"myurl/mydata")
       .WithQueryString("query", query)
       .Respond(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(_mydata) }));

 _mockHttpHandler
        .When($"myurl/mydata?query=foo")
        .WithQueryString("query", query)
        .Respond(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(_mydata) }));

and the requested url is
url = "myurl/mydata?query=foo&other=bar"

I believe the culprit is this line,
https://github.com/richardszalay/mockhttp/blob/master/RichardSzalay.MockHttp.Shared/Matchers/QueryStringMatcher.cs#L44

StatusCode 404

I 'm trying to mock my restful adapter , but I have an exception 404 No matching mock handler

this my code

var httpMockHandler = new MockHttpMessageHandler();
httpMockHandler.When(HttpMethod.Post,"https://api.sandbox.ewaypayments.com/encrypt")
.WithContent(data)
.Respond("application/json",expectedResponse);
var client = new HttpClient(httpMockHandler);
var response = await client.GetAsync("https://api.sandbox.ewaypayments.com/encrypt");
httpMockHandler.VerifyNoOutstandingExpectation();
var result = await response.Content.ReadAsStringAsync();

I dont know what I did wrong,Can you please help me?

Do multiple Expects with a different WithContent

When you try to use the Expect Method with WithContent twice (with different content in WithContent for the 2 queries), the HttpClient mock only detects the first one implemented in the code and the second one isn't seen by calls.

GetAsync vs GetStringAsync

@richardszalay, could you provide insight as to why this test does not pass?

        [TestMethod]
        public async Task Test_MockHttp()
        {
            var mock = new MockHttpMessageHandler();
            var httpClient = new HttpClient(mock);
            mock.Expect("http://localhost.com")
                .Respond(HttpStatusCode.OK);
            await httpClient.GetAsync("http://localhost.com");

            _mockHttp.VerifyNoOutstandingExpectation();
            _mockHttp.Flush();

            mock.Expect("http://localhost.com")
                .Respond(HttpStatusCode.OK, new StringContent("test"));
            var s = await httpClient.GetStringAsync("http://localhost.com");
            Assert.AreEqual("test", s);
            _mockHttp.VerifyNoOutstandingExpectation();
        }

Test Name: Test_MockHttp
Test Outcome: Failed
Test Duration: 0:00:00.0167335

Result StackTrace:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at <Test_MockHttp>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Result Message: Test method Test_MockHttp threw exception:
System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (No matching mock handler).

Effectively, the expectations work with GetAsync but not with GetStringAsync.

Typo in obsolete message

MockedRequestExtensions.Respond(MockedRequest, HttpResponseMessage)' is obsolete: 'Using this overload is not recommended. Instead, use Response(req => new HttpResponseMessage(...))

Response should be Respond.

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.