添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I got the similar problem as issue 200 .

It works fine if run each test individually but when 2 test cases running sequentially I got NoHttpResponseException.

org.apache.http.NoHttpResponseException: localhost:9992 failed to respond
	at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:141)
	at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
	at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
	at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
	at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:165)
	at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
	at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
	at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
	at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
	at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
	at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
	at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
	at com.mytest.mockserver.SampleTest.test2(SampleTest.java:90)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Test Code

import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.*;
import org.junit.runners.MethodSorters;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import java.io.IOException;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SampleTest {
    final private String host = "localhost";
    final private int serverPort = 9992;
    final private String path = "/somepath";
    final private String url = "http://" + host + ":" + serverPort + path;
    private ClientAndServer mockServer;
    static private CloseableHttpClient client;
    @BeforeClass
    public static void start() {
        client = HttpClients.createDefault();
    @AfterClass
    public static void close() throws IOException {
        client.close();
    @Before
    public void startMockServer() {
        mockServer = startClientAndServer(serverPort);
    @After
    public void stopMockServer() {
        mockServer.stop();
    @Test
    public void test1() throws IOException {
        new MockServerClient(host, serverPort)
                .when(
                        request()
                                .withPath(path))
                .respond(
                        response()
                                .withStatusCode(200));
        HttpPost post = new HttpPost(url);
        client.execute(post);
    @Test
    public void test2() throws IOException {
        new MockServerClient(host, serverPort)
                .when(
                        request()
                                .withPath(path))
                .respond(
                        response()
                                .withStatusCode(200));
        HttpPost post = new HttpPost(url);
        client.execute(post);

Dependencies

    <dependencies




    
>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.mock-server</groupId>
            <artifactId>mockserver-netty</artifactId>
            <version>5.3.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

The fix works for me is to wait for mockServer stop completely.

    @After
    public void stopMockServer() throws InterruptedException {
        mockServer.stop();
        // Wait for mockServer to stop fully
        while (mockServer.isRunning()) {
            Thread.sleep(1000L);
          

@yigangzhang
I got same issue with you , and I need to start mockServer in BeforeAll.
Here is my example, and it works

private static OAuth2AppInfo  freshbooksApp;
    private static OAuth2Client oAuth2Client;
    private static ClientAndServer mockServer;
    @BeforeAll
    public static void setUp() {
        mockServer = startClientAndServer(1080);
    @AfterAll
    public static void tearDown() {
        mockServer.stop();
          

This issue is now fixed and will be in the next release 5.5.0. It seems to be related to sockets staying open after Netty has reported they are closed and everything is shutdown. I have fixed this issue by adding a 2 second delay after this which seems to work reliably when tested. However I wouldn't recommend recreating a new instance of MockServer for each test because it is completely unnecessary and is much more expensive then just calling reset. If you just call reset (or clear) before each test and only start and stop the MockServer at the start and end of the suite your tests will run faster and this issue will completely go away.
Although MockServer is very fast at starting up as an analogy if you were testing a web application you wouldn't typically redeploy the web application between each test method how ever fast it was because that is overkill and as your test number increase the time taken to deploy would be significant.

@jamesbloomnektan - when you get a chance, can you please provide more information specifically on the NoHttpResponseException in general (not mockserver in particular)? Based on your experience under what circumstances can this occur? Is this a client fault or a server fault? Does the client need to update anything or does the server? How did you go about finding the root cause and why did you decide to fix it using 2 second delay and where exactly did you add delay?

FYI I have been reading about this specific exception but nothing concrete, example: https://stackoverflow.com/questions/10558791/apache-httpclient-interim-error-nohttpresponseexception and it is not 100% clear if this is a server fault or client fault - since note talks about stale connection on client end which can be half closed. And more importantly very hard to replicate.

Just picking on your brain since you built a server and faced this exact exception :)

I am using 5.11.1 version and observed the same issue. I would like to know why this happens and what could be the fix.

public class MockServerExample {

    /* Set up service endpoint */
    public static String HOST = "127.0.0.1";
    public static int PORT = 1080;
    public static void start() {
            startClientAndServer(PORT);
            createExpectations();
    private static void createExpectation() {
            new MockServerClient(HOST, PORT)
                    .when(
                            request()
                                    .withPath("/path1/ping")
                    .forward(
                            forward()
                                    .withHost("127.0.0.1")
                                    .withPort(9000)
            new MockServerClient(HOST, PORT)
                    .when(
                            request()
                                    .withPath("/path2")
                    .forward(
                            forwardOverriddenRequest(
                                    request()
                                            .withPath("/path2")
                                            .withSocketAddress("127.0.0.1", 60000, SocketAddress.Scheme.HTTP)

It is basically testing request forwarding. Upon receiving the request, it forwards to localhost:60000 with same path. In the @beforeClass, it calls start().

The error I got is:
DEBUG 19:36:31.880 [main] o.a.http.impl.execchain.RetryExec: The target server failed to respond ! org.apache.http.NoHttpResponseException: The target server failed to respond ! at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:141) ~[httpclient-4.5.9.jar:4.5.9] ! at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56) ~[httpclient-4.5.9.jar:4.5.9] ! at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259) ~[httpcore-4.4.11.jar:4.4.11] ...

Seeing the same issue with 5.11.1. A test that runs in isolation consistently fails when run with the rest of the suite with this error:

2021-09-01T19:22:48.830-0400 -DEBUG r: --- [Test worker] o.s.web.client.RestTemplate              : Writing [CreateIncident([email protected], ...)] with org.springframework.http.converter.json.MappingJackson2HttpMessageConverter  [appVersion=0.241.0-dev.3.uncommitted.STARK.2061.customer.repository.8770f7b, appName=stark-appointment-service]
2021-09-01T19:22:48.843-0400 -ERROR r: --- [Test worker] com.company.ChatServiceImpl     : I/O error on POST request for "http://localhost:27910/chat/api/v1/appointments": localhost:27910 failed to respond; nested exception is org.apache.http.NoHttpResponseException: localhost:27910 failed to respond org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:27910/chat/api/v1/appointments": localhost:27910 failed to respond; nested exception is org.apache.http.NoHttpResponseException: localhost:27910 failed to respond
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785)
	at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:660)
	at com.company.ChatServiceImpl.lambda$createIncident$0(ChatServiceImpl.java:44)
	at reactor.core.publisher.MonoCallable.subscribe(MonoCallable.java:57)
	at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64)
	at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:157)
	at reactor.core.publisher.FluxPeek$PeekSubscriber.onNext(FluxPeek.java:200)
Caused by: org.apache.http.NoHttpResponseException: localhost:27910 failed to respond
	at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:141)
	at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
	at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
	at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
	at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
	at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
	at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
	at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
	at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
	at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
	at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
	at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)

There is no log output whatsoever from the ClientAndServer.

I have the same issue with 5.13.2.

Running single test works, even running 2-5 tests sequentially works, but running all tests (30 atm) at least one (always the same) fails with org.apache.http.NoHttpResponseException: 127.0.0.1:11111 failed to respond.

I reset MockServer in @AfterEach so every test starts with a clean MockServer, but one of them (its always the same) fails. Also no log output from MockServer, seems like it is either dropping the request or not even receiving it for whatever reason.

After adding a Thread.sleep(1000L) in a @BeforeEach all tests succeed.

Sounds like something is happening asynchronously when reset() (or when(...).respond(...)) is called.

Are you using Spring WebFlux or do you have some other interesting asynchronicity in your application? Every time I've suspected MockServer was dropping the ball, it turned out to be some gnarly race condition in my application code that was deadlocking or similar.. Just my $0.02. (I posted the comment right above yours.)

@jamesbloomnektan - when you get a chance, can you please provide more information specifically on the NoHttpResponseException in general (not mockserver in particular)? Based on your experience under what circumstances can this occur? Is this a client fault or a server fault? Does the client need to update anything or does the server? How did you go about finding the root cause and why did you decide to fix it using 2 second delay and where exactly did you add delay?

FYI I have been reading about this specific exception but nothing concrete, example: https://stackoverflow.com/questions/10558791/apache-httpclient-interim-error-nohttpresponseexception and it is not 100% clear if this is a server fault or client fault - since note talks about stale connection on client end which can be half closed. And more importantly very hard to replicate.

Just picking on your brain since you built a server and faced this exact exception :)

did you get a answer for this we are also facing same issue