Giter Club home page Giter Club logo

httpclientmock's Introduction

Maven Central Maven Central

HttpClientMock

HttpClientMock is a library for mocking Apache HttpClient. It has an intuitive API for defining client behaviour and verifying number of made requests. It works with HttpClient 4.X and 5.X.

Installation

HttpClientMock is available in Maven Central Repository. Maven Central

  • For mocking HttpClient 4.x use HttpClientMock 1.X.
  • For mocking HttpClient 5.x use HttpClientMock 2.X.

Usage

Record

Working with HttpClientMock starts with defining client behaviour. Before code under tests starts HttpClientMock must know how to respond to every request.

HttpClientMock httpClientMock = new HttpClientMock();
httpClientMock.onGet("http://localhost/login")
  .withParameter("user","john")
  .doReturn("Ok");
httpClientMock.onPost("http://localhost/login").doReturnStatus(501);

Replay

Code under test starts and uses HttpClientMock with defined behaviour.

httpClient.execute(new HttpGet("http://localhost/login?user:john")); // returns response with body "Ok"
httpClient.execute(new HttpPost("http://localhost/login")); // returns response with status 501

Verify

When code under test finishes, HttpClientMock allows to check number of made request. It is possible to use the same set of conditions as for defining mock behaviour.

httpClientMock.verify().get("http://localhost/login").withParameter("user","john").called();
httpClientMock.verify().post("http://localhost/login").notCalled();

Request matching

HTTP method

HttpClientMock supports all Http methods.

httpClientMock.onGet().doReturn("get");
httpClientMock.onPost().doReturn("post");
httpClientMock.onPut().doReturn("put");
httpClientMock.onDelete().doReturn("delete");
httpClientMock.onOptions().doReturn("options");
httpClientMock.onHead().doReturn("head");

URL

Every onGet(), onPost(), .... method accept URL. It is possible to write:

httpClientMock.onGet("http://localhost/login?user=john").doReturnStatus(200);

which is equal to

httpClientMock.onGet()
  .withHost("http://localhost")
  .withPath("/login")
  .withParameter("user","john")
  .doReturnStatus(200);

It is possible to define default host using HttpClientMock constructor, so later methods can accept relative URL-s.

HttpClientMock httpClientMock = new HttpClientMock("http://localhost");
httpClientMock.onGet("/login").doReturn("ok");
httpClientMock.onPost("/edit?user=john").doReturnStatus(200);

httpClientMock.onGet("http://www.google.com").doReturn("Google") // Absolute paths still work.

Host, path, parameters conditions

It is possible to define each part of url separately.

httpClientMock.onGet()
  .withHost("http://localhost")
  .withPath("/login")
  .withParameter("user","john")
  .doReturnStatus(200);

Header condition

httpClientMock.onGet("http://localhost/login")
  .withHeader("tracking","123")
  .doReturn("ok");

Form parameters

httpClientMock.onPost("/login")
      .withFormParameter("username", "John")
      .withFormParameter("password", Matchers.containsString("secret"))
    .doReturnStatus(200);

Body condition

httpClientMock.onGet("http://localhost/login")
  .withBody("tracking",containsString("123"))
  .doReturn("ok");

Custom condition

Condition fooCondition = request -> request.getUri().contains("foo");
httpClientMock.onGet("http://localhost/foo/bar")
  .with(fooCondition)
  .doReturn("yes");

Matchers

Every condition method accepts Hamcrest Matcher which allows to define custom conditions on requests.

httpClientMock.onGet("http://localhost")
  .withPath(containsString("login"))
  .withParameter("user",equalToIgnoringCase("John"));

Multiple matching rules

If request matches more then one rule, then last defined one is used.

None rule matche

If request doesn't matche any rule, HttpClientMock return response with status 404.

Define response

Response

Response with provided body and status 200.

httpClientMock.onGet("http://localhost").doReturn("my response");

Status

Response with empty body and provided status

httpClientMock.onGet("http://localhost").doReturnStatus(300);
httpClientMock.onGet("http://localhost").doReturn("Overloaded").withStatus(500);

Exception

Instead of returning response it throws defined exception.

httpClientMock.onGet("http://localhost").doThrowException(new IOException());

Custom action

Action echo = r -> {
  HttpEntity entity = ((HttpEntityEnclosingRequestBase) r.getHttpRequest()).getEntity();
  BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("http", 1, 1), 200, "ok");
  response.setEntity(entity);
  return response;
};
httpClientMock.onGet("http://localhost").doAction(echo);

Response header

httpClientMock.onPost("/login").doReturn("foo").withHeader("tracking", "123");

Response status

httpClientMock.onPost("/login?user=bar").doReturn("Wrong user").withStatus(403);

JSON

Response with provided body, status 200 and content type "application/json"

httpClientMock.onPost("/login").doReturnJSON("{foo:1}");

XML

Response with provided body, status 200 and content type "application/xml"

httpClientMock.onPost("/login").doReturnXML("<foo>bar</foo>");

Multiple actions

It is possible to add multiple actions to one rule. Every call will use next action until last is reached.

httpClientMock.onPut("/addUser")
  .doReturn("ok")
  .doReturnStatus(500);

httpClientMock.execute(new HttpPut("http://localhost/addUser")); //returns "ok"
httpClientMock.execute(new HttpPut("http://localhost/addUser")); //returns status 500
httpClientMock.execute(new HttpPut("http://localhost/addUser")); //returns status 500

Verification

HttpClientMock allows to check how many calls were made. Verification supports the same set of conditions us rule defining.

httpClientMock.verify().get("http://localhost").called();

httpClientMock.verify().get("http://localhost/login")
  .withParameter("user","john")
  .called();

httpClientMock.verify().get("http://localhost/login")
  .withParameter("user","Ben")
  .notCalled();

httpClientMock.verify().delete().notCalled();

httpClientMock.verify().get().called(greaterThanOrEqualTo(1));

Matching query and form parameters

There are two methods that control HttpClientMock behaviour when request contains extra form or query parameters:

  • withExtraParameters: allows request to contain extra query parameters
  • withoutExtraParameters: disallows request to contain extra query parameters
  • withExtraFormParameters: allows request to contain extra form parameters
  • withoutExtraFormParameters: disallows request to contain extra form parameters

Examples:

httpClientMock.onPost("/login")
  .withParameter("user","John")
  .withoutExtraParameters()
  .doReturn("ok");

Above condition will not match request http://www.example.com/login?user=John&password=secret because it contains extra parameter password.

httpClientMock.onPost("/login")
  .withParameter("user","John")
  .withExtraParameters()
  .doReturn("ok");

Above condition will match request http://www.example.com/login?user=John&password=secret although it contains extra parameter password.

By default HttpClientMock matches requests with extra form and query parameters.

Debugging

HttpClientMock can help you to debug your code by displaying information which matchers matched your request. You can use HttpClientMock#debugOn to turn it on and HttpClientMock#debugOff to turn it off. Example message:

Rule 1:
	MATCHES		EXPECTED
	true		HTTP method is GET
	true		schema is "http"
	true		host is "localhost"
	false		path is "/login"
	true		port is empty

Example 1

// DEFINE BEHAVIOUR
HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080");
httpClientMock.onGet("/login?user=john").doReturnJSON("{permission:1}");
httpClientMock.onPost("/edit")
  .withParameter("user","John")
  .doReturn("ok")
  .doReturnStatus(503);

// EXECUTION
// request to http://localhost:8080/login?user=john returns JSON {permission:1}
// first request to http://localhost:8080/edit?user=john returns message "ok"
// second request to http://localhost:8080/edit?user=john returns request with status 503

// VERIFICATION
httpClientMock.verify().get("/login?user=john").called();
httpClientMock.verify().post("/edit?user=john").called(2);
httpClientMock.verify().delete().notCalled();

Example 2

// DEFINE BEHAVIOUR
HttpClientMock httpClientMock = new HttpClientMock();
httpClientMock.onGet("http://localhost:8080/login").doReturn("Missing parameter user").withStatus(400);
httpClientMock.onGet("http://localhost:8080/login")
  .withParameter("user","JJohn")
  .doReturn("Wrong user name").withStatus(403);
httpClientMock.onGet("http://localhost:8080/login")
  .withParameter("user","John")
  .doReturn("ok");
  
// EXECUTION
// request to http://localhost:8080/login?user=john returns message "ok"

// VERIFICATION
httpClientMock.verify().get("/login?user=john").called();

Release notes

2.1.1

  • Fixed MalformedURLException when using not absolute paths

2.1.0

  • Added method withStatus accepting status code and text

2.0.0

  • Added support for HttpClient 5.
  • Removed methods for mocking URL reference

1.9.1

  • Fixed MalformedURLException when using not absolute paths

1.9.0

  • Added method withStatus accepting status code and text

1.8.0

  • Added methods {withExtraParameters, withoutExtraParameters, withExtraFormParameters, withoutExtraFormParameters} to better control form and query parameters matching. WARNING Breaking changes: Since this version by default HttpClientMock matches requests with extra form and query parameters.

1.7.0

  • Added methods (withFormParameter, withFormParameters) for matching form parameters (URL encode parameters).
  • Added action (doReturnFormParams) which return response with body containing provided form parameters.

1.6.0

  • Added possibility to set response Content-Type.
  • Fixed wrong Contet-Type in methods 'doReturnXML', doReturnJSON

1.5.0

  • Added possibility to add cookies to the response.

httpclientmock's People

Contributors

bachkovsky-git avatar basalt79 avatar beonit avatar borisingithub avatar dependabot[bot] avatar huyle1097 avatar mangstadt avatar paweladamski avatar pomu0325 avatar snyk-bot 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

Watchers

 avatar  avatar  avatar  avatar

httpclientmock's Issues

Matching should ignore redundant or additional parameters

Hi Pawel,

Thank you for your awesome library, it has has brought great value in numerous projects already. 👍🏻Hence, dare I make a feature request?

Problem

For some of my use cases the matching of an URL is too strict. If the actual URL contains any parameters, it seems I have to record expectations with exactly the their names, or they won't match.

Hopefully an example will illustrate my point. I created following locally in the same style as other tests in your HttpClientMockBuilderTest to demonstrate the use case I'd like to work.

  @Test
  public void should_match_any_parameter_value() throws IOException {
    HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080");

    httpClientMock
            .onGet("/foo")
            .doReturn("whatever");

    HttpResponse one = httpClientMock.execute(new HttpGet("http://localhost:8080/foo?id=1&name=abc"));
    HttpResponse two = httpClientMock.execute(new HttpGet("http://localhost:8080/foo?id=2"));

    assertThat(one, hasStatus(200));
    assertThat(two, hasStatus(200));
  }

As no other you know why this test actually fails with 404's ;-) The debug output shows some of the conditions don't match:

Request: GET http://localhost:8080/foo?id=1&name=abc
Rule 1:
	MATCHES		EXPECTED
	true		HTTP method is GET
	true		schema is "http"
	true		host is "localhost"
	true		path is "/foo"
	true		port is <8080>
	false		parameter id is redundant
	false		parameter name is redundant

----------------
Request: GET http://localhost:8080/foo?id=2
Rule 1:
	MATCHES		EXPECTED
	true		HTTP method is GET
	true		schema is "http"
	true		host is "localhost"
	true		path is "/foo"
	true		port is <8080>
	false		parameter id is redundant

"parameter id is redundant". By default, when actual parameters "id" and "name" are present, none of the rules match, because I didn't explicitly specify them.

A naive solution seems to be listing each and every possible parameter by name, ignoring whatever value they have, such as:

httpClientMock
    .onGet("/foo")
    .withParameter("id", Matchers.any(String.class))
    .withParameter("name", Matchers.any(String.class))
    .doReturn("whatever");

but now the 2nd request http://localhost:8080/foo?id=2 fails, because "parameter name occurs in request".

In my primary use case above, I want any request on /foo to match (and return "whatever"), no matter the parameters.

  • I don't care about the parameters for some of my tests, and I'd rather not have to specify them by name at all if I don't have too.
  • Right now I'm forced to "duplicate" multiple mock requests just because of the variation of parameters which sometimes are not relevant at all.

I have not found a way to ignore any redundant or additional parameters, so if there ís I hope you can point me in the right direction and skip the rest of my request below :-)

Feature request

Could you allow me in my tests to match parameters more leniently and give me the option to ignore redundant/additional parameters?

Suggestion

Making the default behaviour of HttpClientMock with regard to parameter matching more lenient is due to backwards-compatibility concerns not advisable, but maybe this can be specified either on the mock itself, or as part of the conditions, to enable the desired behaviour of not failing on irrelevant parameters.

E.g. to make above test pass, one could use a new withAnyParameter method:

httpClientMock
        .onGet("/foo")
        .withAnyParameter()
        .doReturn("whatever");

(allowing in the future additional similar methods e.g. withAnyReference etc.)

Or there could be an option to match on the name of a parameter with a Hamcrest matcher, by introducing a withParameter(Matcher<String> nameMatcher) allowing to match the existince something specific or -- in my case -- "anything".

httpClientMock
    .onGet("/foo")
    .withParameter(Matchers.any(String.class))
    .doReturn("whatever");

In this case you'd still have a parameter condition under the hood.

In any case, you'd have to see whatever doesn't interfere too much with the existing underlying rule-matching logic. I'm happy to think along, if you need to! 👍

How to mock HTTP response of Zip file - Getting java.io.EOFException

Do we have any sample for mocking HTTP response of zip file?

I tried to mock response of zip but I am getting java.io.EOFException, looks like stream already consumed. I might be doing something wrong. Can you please suggest me any clue for this issue?

Sample Code

Action action = new Action() {
	@Override
	public HttpResponse getResponse(Request request) throws IOException {
		BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("http", 1, 1), status, statusMessage);
		FileEntity entity = new FileEntity(new File("C:/sample-response.zip"));
		response.setEntity(entity);
		return response;
	}
};

HttpClientMock httpClientMock = new HttpClientMock();
Unirest.config().httpClient(ApacheClient.builder(httpClientMock));

httpClientMock.onGet("http://xxx.com").doAction(action);

// Rest Request Initiated

// Used code to download

HttpGet httpGet = new HttpGet(downloadLocation);
httpGet.addHeader(AUTHORIZATION, "TOKEN");
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();

InputStream content = entity.getContent();
LOGGER.info("** Stream length '{}'", content.available());  // 'content.available()' throwing java.io.EOFException

Exception stackTrace

java.io.EOFException
	at java.util.zip.GZIPInputStream.readUByte(GZIPInputStream.java:268)
	at java.util.zip.GZIPInputStream.readUShort(GZIPInputStream.java:258)
	at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:164)
	at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:79)
	at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:91)
	at org.apache.http.client.entity.GZIPInputStreamFactory.create(GZIPInputStreamFactory.java:61)
	at org.apache.http.client.entity.LazyDecompressingInputStream.initWrapper(LazyDecompressingInputStream.java:51)
	at org.apache.http.client.entity.LazyDecompressingInputStream.available(LazyDecompressingInputStream.java:86)

Maven details -
HttpClientMock - 1.8.1 (I know it's year old version, if you have any sample with latest verion for ZIP file then please share)

Java 11 native HttpClient version

Hi there!

I came across a related project called HttpClientMock that you were also involved in: PGSSoft/HttpClientMock#3

This project is great and from what I can tell, it's the only productive option for mocking the Java 11 native HttpClient. (Aside from rolling-your-own similar solution.)

I'm planning to fork that project in a couple weeks, unless you're interested in owning it:

PGSSoft/HttpClientMock#3

Thanks,
J.R.

NPE when the scheme is not set for version 1.10.0

I am seeing an NPE with the following test with version 1.10.0. This issue is not reproducible with version 2.2.1. However, I am currently stuck on 1.10.0 for my application.

    @Test
    public void npeWhenSchemeIsNotSet() throws Exception {
        final URI uri = new URIBuilder().setHost("foo").setPath("/example").build();
        final HttpPost post = new HttpPost(uri);

        try (HttpClientMock client = new HttpClientMock()) {
            client.onPost("http://foo/example").doReturn("1");
            client.execute(post);
        }
    }

uri does not specify a scheme.

The above code outputs:

java.lang.NullPointerException
	at com.github.paweladamski.httpclientmock.Request.getUri(Request.java:39)
	at com.github.paweladamski.httpclientmock.Rule.matches(Rule.java:32)
	at com.github.paweladamski.httpclientmock.Rule.matches(Rule.java:38)
	at com.github.paweladamski.httpclientmock.HttpClientMock.lambda$getHttpResponse$0(HttpClientMock.java:267)
	at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:176)
	at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
	at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.reduce(ReferencePipeline.java:558)
	at com.github.paweladamski.httpclientmock.HttpClientMock.getHttpResponse(HttpClientMock.java:268)
	at com.github.paweladamski.httpclientmock.HttpClientMock.doExecute(HttpClientMock.java:248)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
	at io.github.emaccaull.httpclient.ClientMockTest.npeWhenSchemeIsNotSet(ClientMockTest.java:19)

When a more helpful error message would be nice and save debugging time.

Thank you for this project. It's been very helpful.

Missing the possibility of adding interceptors

Currently, interceptors behavior has to be faked for each end every mocked request. If a dev decides to use interceptors on the actual HttpClient, he/she needs to code a lot for the sake of tests.
The very same interceptors (same interfaces) should be possible to add to the HttpClientMock class via builder - just like HttpClientBuilder's methods:

HttpClientBuilder.addInterceptorFirst(org.apache.http.HttpRequestInterceptor itcp)
HttpClientBuilder.addInterceptorFirst(org.apache.http.HttpResponseInterceptor itcp)
HttpClientBuilder.addInterceptorLast(org.apache.http.HttpRequestInterceptor itcp)
HttpClientBuilder.addInterceptorLast(org.apache.http.HttpResponseInterceptor itcp)

Add mocking of HttpAsyncClient

Currently HttpClientMock supports only mocking of HttpClient. In scope of this issue we want to add support for mocking HttpAsyncClient. Working HttpAsyncClientMock should look similar to HttpClientMock. Example:
Record:

HttpClientAsyncMock httpClientAsyncMock = new HttpClientAsyncMock();
httpClientAsyncMock .onGet("http://localhost/login")
  .withParameter("user","john")
  .doReturn("Ok");
httpClientAsyncMock .onPost("http://localhost/login").doReturnStatus(501);

verify:

httpClientAsyncMock .verify().get("http://localhost/login").withParameter("user","john").called()
httpClientAsyncMock .verify().post("http://localhost/login").notCalled()

HttpClientAsyncMock should have additional action to simulate a delay response.

httpClientAsyncMock .onPost("http://localhost/login").delay(4,TimeUnit.Seconds).doReturnStatus(501);

Feature: Reuse HttpClientResponseBuilder for verification

Currently i have to rewrite the mock rule to verify the number of calls. I.e.:

mock.onPost().withPath(Matchers.containsString("/something")).doReturn(HttpStatus.SC_OK, "777");
[...]
mock.verify().post().withPath(Matchers.containsString("/something")).called(1);

Especially when using complex rules this is time consuming and a maintenance issue.
I would like to reuse the rule, for example like this:

HttpClientResponseBuilder builder = mock.onPost().withPath(Matchers.containsString("/something")).doReturn(HttpStatus.SC_OK, "777");;
[...]
mock.verify(builder).called(1);

When user set status NO_CONTETNT HttpEntity should be null.

HttpClientMock should follow Apache Http Client behavior so with following setup:

 HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080");
 httpClientMock.onPut("/save").doReturnStatus(204);

calling httpClientMock.execute(httpGet("http://localhost:8080/save")).getEntity() should return null.

Unable to reset stubs between tests

Thank you for all your work on this project. Much easier and more intuitive than hacking around with mockito (in this case).

I'm currently having an issue of rules defined in one test being picked up by others tests. For example I might have a test like this:

 @Test
      void some_test_1() {

        httpClientMock.onGet()
            .withPath(containsString("cars"))
            .doReturn("")
            .withStatus(404);

       // request to some other service that would eventually call httpClientMock
        var response = testRestTemplate.exchange(
            "/v001/someOtherServicePath",
            HttpMethod.GET,
            null,
            String.class);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
      }

and another test:

 @Test
      void some_test_2() {

        httpClientMock.onGet()
            .withPath(containsString("cars"))
            .doReturn("")
            .withStatus(503);

       // request to some other service that would eventually call httpClientMock
        var response = testRestTemplate.exchange(
            "/v001/someOtherServicePath",
            HttpMethod.GET,
            null,
            String.class);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
      }

matching rules output, might look like this (NB I know this is showing the rules don't match in this case - I'm just highlighting that 2 rules appear from different tests...)

Rule 1:
MATCHES EXPECTED
false HTTP method is GET
true schema is an instance of java.lang.String
true host is
false path is a string containing "cars"
true port is empty
Rule 2:
MATCHES EXPECTED
false HTTP method is GET
true schema is an instance of java.lang.String
true host is
false path is a string containing "cars"
true port is empty

Using httpClientMock.reset() via a BeforeEach does not appear to make any difference.

When I run the tests individually they pass as expected however when I run them altogether via maven or in intellij they fail, as unrequired rules and stubs seem to be picked up from others tests.

I'm using spring boot @SpringBootTest and have HttpClientMock autowired in as a bean.

Any help/advice appreciated.

Handle url-s with parameter

mock.post("http://www.example.com?foo=bar")
should be equivalent to
mock.post("http://www.example.com").withParameter("foo","bar")

Apache HTTP Client 5

Hello!

Do you have any plans to support Apache Http Client 5? I realize it's a bid deal as it rewrites huge chunks.

Thanks for the great library BTW I use it all the time,

Ryan

Add support for URL-encoded form parameters?

This is referring to the parameters that are typically found in the body of POST requests when you submit a <form> on a website.

HttpClientMock client = new HttpClientMock();

//request body looks like: username=John&password=secret%21
//content type is: application/x-www-form-urlencoded

client.verify().post("/login")
  .withBodyParameter("username", "John")
  .withBodyParameter("password", "secret!")
.called();

//or maybe

client.verify().post("/login")
  .withBody(
    new BasicNameValuePair("username", "John"),
    new BasicNameValuePair("password", "secret!")
  )
.called();

I have started looking at the codebase and working on a solution. Do you think this would be useful? Can HttpClientMock already do this?

Add possibility to set HTTP status text

Currently, it is not possible to mock the status text of the HTTP response. For now it is always either "ok" or "" depending on which method was used to build the response. In the current version method, withStatus accepts only code which is used to build the HTTP response. I would like to have another version of that method that will accept code and text.
E.g.

httpClientMock.onPost("testUlr").doReturn("some message").withStatus(409, "reason");

Acceptance criteria:

  • new method withStatus(code, reason) should be added to HttpClientResponseBuilder
  • StatusResponse constructor should accept both status and reason text

doReturnJSON responses are rendered with Content Type `text/plain`

Thanks for providing this, very helpful 👍

I ran into an issue when using doReturnJson(): Content-Type application/json appears to be added as a response header instead of an entity header. A default entity header Content-Type text/plain is added by StringEntity, which can lead to problems when processing the response.

As a work-around we can use a custom Action response to create the StringEntity with the correct mime-type, so it's only a minor issue.

Ability to set no Response Entity

https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpResponse.html#getEntity()
=> Returns: the response entity, or null if there is none

I couldn't find a way to use HttpClientMock to create an response without entity so i would get an null reponse from this method.
I tried "doReturn(200, null)" but this results in an exception in Apache HttpClient

java.lang.IllegalArgumentException: Source string may not be null at org.apache.http.util.Args.notNull(Args.java:54) at org.apache.http.entity.StringEntity.<init>(StringEntity.java:65) at org.apache.http.entity.StringEntity.<init>(StringEntity.java:132) at com.github.paweladamski.httpclientmock.action.StringResponse.getResponse(StringResponse.java:40) at com.github.paweladamski.httpclientmock.Rule.nextResponse(Rule.java:43) at com.github.paweladamski.httpclientmock.HttpClientMock.getHttpResponse(HttpClientMock.java:273) at com.github.paweladamski.httpclientmock.HttpClientMock.doExecute(HttpClientMock.java:248)

Path matching does not work with special chars like semicolon in URL (matrix parameters)

If the path contains a semicolon the path matching does not work, i.e.
http://myHost/api/x;myParam1=a;myParam2=b

...withPath(Matchers.containsString("api/x;myParam1=a;myParam2=b"))
=> Rule does not match

...withPath(Matchers.containsString("myParam1=a;myParam2=b"))
=> Rule does not match

...withPath(Matches.containsString("http://myHost/api/x"))
=> Rule DOES match

I found similar issues when escape characters are used in the url for whitespace, ?, & and others

How can reture HTTP status message

Hi Team,

I need to return specific HTTP status message instead of default ok.

E.g - 1. 409 - Conflict
2. 400 Bad Request

i tried wth below code snippet but is returning 'ok' instead of 'conflict' while calling getStatusText() operation,.

httpClientMock.onPost("testUlr").doReturn(409, "some message");

Could you please suggest any way to set status text as well?

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.