Git Product home page Git Product logo

mock-server / mockserver Goto Github PK

View Code? Open in Web Editor NEW
4.5K 125.0 1.0K 50.7 MB

MockServer enables easy mocking of any system you integrate with via HTTP or HTTPS with clients written in Java, JavaScript and Ruby. MockServer also includes a proxy that introspects all proxied traffic including encrypted SSL traffic and supports Port Forwarding, Web Proxying (i.e. HTTP proxy), HTTPS Tunneling Proxying (using HTTP CONNECT) and SOCKS Proxying (i.e. dynamic port forwarding).

Home Page: http://mock-server.com

License: Apache License 2.0

Ruby 0.07% Shell 0.75% HTML 10.59% CSS 0.01% JavaScript 1.57% Java 86.68% FreeMarker 0.02% Dockerfile 0.14% SCSS 0.17% Mustache 0.01%
mock-server proxy java-client javascript-client node-module node-client ruby-client homebrew grunt-plugin

mockserver's People

Contributors

acheaito avatar albans avatar amcvitty avatar arkinator avatar bby-bishopclark avatar bhmohanr-techie avatar brcolow avatar cecedille1 avatar dependabot[bot] avatar derpauli avatar ganskef avatar jamesbloomnektan avatar jamesdbloom avatar jekh avatar jnormington avatar jsoref avatar manueldeveloper avatar micst96 avatar mockserver-bamboo-build avatar nayyara-cropsey avatar nitram509 avatar pascal-hofmann avatar reitzig avatar richardfisk avatar richardpfisk avatar rs017991 avatar slawekib avatar snorkell avatar snyk-bot avatar vampire 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  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

mockserver's Issues

Multi threaded delays

Hi James,

I have been using delays and I ran into another possible issue. When I set the delay to 5 seconds and run 2 threads against the Mockserver, responses will take 10 seconds and not 5 seconds each.

Am I configuring the delay wrongly? I have added the following to my JSON create expectation:
"delay": {
"timeUnit": "SECONDS",
"value": 5
}

Thanks,

Jeroen

port Jetty Server to Netty

Porting Jetty Server to Netty will:

  • support Java 1.6
  • simplify SOCKS proxy
  • simplify Http CONNECT support and allow solution for Vert.X to use the same code
  • improve performance and reliability of proxy

PDF content missing when sent as response body

Hi James,

I'm having a little trouble with sending a response with a PDF as the body content.

The setup I'm using is as follows:

this.mockServer.when(request().withPath("/ws/rest/user/[0-9]+/document/[0-9]+\\.pdf"))
    .respond(response().withBody(Files.toByteArray(new File("src/main/resources/MyDocument.pdf")))
        .withStatusCode(HttpStatusCode.OK_200.code())
        .withHeaders(
            new Header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()),
            new Header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"output.pdf\"; filename=\"output.pdf\""),
            new Header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0")
        )
    );

But when I receive the response in my code under test it seems that some of the PDF content is missing and I get a malformed PDF. I find the same thing if I start up the test and then hit the MockServer endpoint with my browser.

A similar setup using Spring-MVC works fine:

@RequestMapping(value = "/ws/rest/user/{userId}/document/{documentId}.pdf", method = RequestMethod.GET)
public ResponseEntity<byte[]> mockResponse() throws IOException {
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    final String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    final ResponseEntity<byte[]> response =
            new ResponseEntity<byte[]>(Files.toByteArray(new File("src/main/resources/MyDocument.pdf")), headers, HttpStatus.OK);
    return response;
}

Is there something I'm missing from my MockServer setup?

Add method to stop Jetty's HttpClient

In case of running MockServerClient in a standalone application, Jetty HttpClient's threads prevent application from quitting, despite of the fact that main thread has ended its work.

Extending API (with httpClient.stop() call) would solve the problem, as it works for me (I did that with use of reflection).

Error message when I use regex pattern

Hello,

I'm using mock server ver.2.9.
When I use code as following, it works as expected.
But mock server prints error log as following.
Can I ignore this log?

Error log

3859 [nioEventLoopGroup-3-2] ERROR org.mockserver.matchers.RegexStringMatcher  - Error while matching regex [{"test":"foobar"}] for string [.*"test":".*".*] Illegal repetition
{"test":"foobar"}

Test code

public class MockServerTest {
    private static final String HOST = "localhost";
    private static final int PORT = 9999;
    private static ClientAndServer mockServer;

    @BeforeClass
    public static void beforeClass() {
        mockServer = startClientAndServer(PORT);
    }

    @AfterClass
    public static void afterClass() {
        mockServer.stop();
    }

    @Test
    public void test() throws Throwable {
        final String requestBodyRegExp = ".*\"test\":\".*\".*";
        final String resource = "/test";
        final String responsedBody = "{\"message\":\"foobar\"}";

        new MockServerClient(HOST, PORT)
        .when(
                request()
                        .withMethod("POST")
                        .withPath(resource)
                        .withBody(StringBody.regex(requestBodyRegExp)),
                Times.exactly(1)
        )
        .respond(
                response()
                        .withStatusCode(200)
                        .withHeaders(
                                new Header("Content-Type", "application/json; charset=utf-8")
                        )
                        .withBody(responsedBody)
                        .withDelay(new Delay(TimeUnit.SECONDS, 1))
        );

        URL restServiceURL = new URL("http://"+HOST+":"+PORT+resource);

        HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL
                .openConnection();
        httpConnection.setDoOutput(true);
        httpConnection.setRequestMethod("POST");

        String input = "{\"test\":\"foobar\"}";;
        OutputStream outputStream = httpConnection.getOutputStream();
        outputStream.write(input.getBytes());
        outputStream.flush();

        if (httpConnection.getResponseCode() != 200) {
            throw new RuntimeException(
                    "HTTP GET Request Failed with Error code : "
                            + httpConnection.getResponseCode());
        }

        BufferedReader responseBuffer = new BufferedReader(
                new InputStreamReader((httpConnection.getInputStream())));
        StringBuilder b = new StringBuilder();
        String line;
        while ((line = responseBuffer.readLine()) != null) {
            b.append(line);
        }

        assertThat(b.toString(), is(responsedBody));
    }

}

replace maven-invoker-plugin with hand crafted plugin integration tests

maven-invoker-plugin is not very reliable or straightforward to use and does not meet all the required use cases. In particular maven-invoker-plugin does not execute unit tests that are part of an integration-test maven project (even though it is supposed to be running mvn package).

To the simplest way to resolve this is to create a simple integration test that runs the sample project (including tests) and passes or fails based on the process return code and the presence of the log file. In addition if the test fails the console output should show the result of the maven execution.

Dependency question

It seems project mockserver-jetty depends on an hypothetic JAR dependency named mockserver-war

        <dependency>
            <groupId>org.mock-server</groupId>
            <artifactId>mockserver-war</artifactId>
        </dependency

But mockserver-war is defined as WAR packaging:

    <artifactId>mockserver-war</artifactId>
    <packaging>war</packaging>

Verify only possible via client JAVA API?

Hi James,

Can I only verify request using the client API?
In mockserver-war (and mockserver-proxy-war) I can't find a verify operation.

The documentation only talks about the Java implementation.

Thanks in advance,
Robert

Verifying multiple requests made during one call

Hi,

My code under test makes more than one http call.

I've set up expectations so that the code under test is performing as expected but I can only pass one request to verify (mockServer.verify(request()...)

I can successfully verify the first request, but no others.

Am I missing something?

-Lee

port Jetty Http Client code to Apache Http Client

Tests have shown that Apache Http Client is more reliable and returns more usable exceptions when issues occur. Porting from Jetty Http Client to Apache Http Client will improve the reliability and performance of the proxy, proxy client and server client.

Warning is flooding log when retrieving a request/response.

When trying to set an expectation:

PUT http://myserver:myport/mock/retrieve HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/json;charset=UTF-8
Content-Length: 340
Host: myserver:myport
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

{
"method": "POST",
"path": "/elementair/AanvraagService/1.2",
"body": {
"type": "XPATH",
"value": "//ZaakAanduiding='2011095'"
},
"headers": [
{
"name": "Content-Type", "values": [".action="./raadpleeg".*"]
}
]

}

we get a warning in the log which looks like this:
14:26:37.821 [[ACTIVE] ExecuteThread: '17' for queue: 'weblogic.kernel.Default (self-tuning)'] WARN o.m.matchers.XPathStringMatcher - SAXParseException while performing match between [//ZaakAanduiding='2011095'] and []
org.xml.sax.SAXParseException: Premature end of file.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195) ~[na:1.6.0_51]
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:174) ~[na:1.6.0_51]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:388) [na:1.6.0_51]
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1427) [na:1.6.0_51]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1056) [na:1.6.0_51]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:647) [na:1.6.0_51]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511) [na:1.6.0_51]
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808) [na:1.6.0_51]
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737) [na:1.6.0_51]
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119) [na:1.6.0_51]
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:232) [na:1.6.0_51]
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284) [na:1.6.0_51]
at weblogic.xml.jaxp.RegistryDocumentBuilder.parse(RegistryDocumentBuilder.java:163) [weblogic.jar:10.3.6.0]
at org.mockserver.matchers.XPathStringMatcher.matches(XPathStringMatcher.java:62) [mockserver-core-2.10.jar:na]
at org.mockserver.matchers.XPathStringMatcher.matches(XPathStringMatcher.java:22) [mockserver-core-2.10.jar:na]
at org.mockserver.matchers.HttpRequestMatcher.matches(HttpRequestMatcher.java:131) [mockserver-core-2.10.jar:na]
at org.mockserver.matchers.HttpRequestMatcher.matches(HttpRequestMatcher.java:102) [mockserver-core-2.10.jar:na]
at org.mockserver.proxy.filters.LogFilter.retrieve(LogFilter.java:107) [mockserver-core-2.10.jar:na]
at org.mockserver.server.MockServerServlet.doPut(MockServerServlet.java:74) [_wl_cls_gen.jar:na]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:730) [javax.servlet_1.0.0.0_2-5.jar:2.5]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) [javax.servlet_1.0.0.0_2-5.jar:2.5]
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227) [weblogic.jar:10.3.6.0]
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125) [weblogic.jar:10.3.6.0]
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301) [weblogic.jar:10.3.6.0]
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26) [weblogic.jar:10.3.6.0]
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60) [BUG16619891_1036.jar:10.3.6.0]
at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:119) [jps-ee.jar:na]
at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:324) ~[jps-api.jar:na]
at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:460) ~[jps-ee.jar:na]
at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:103) ~[jps-ee.jar:na]
at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:171) ~[jps-ee.jar:na]
at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71) ~[jps-ee.jar:na]
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60) [BUG16619891_1036.jar:10.3.6.0]
at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:163) ~[dms.jar:na]
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60) [BUG16619891_1036.jar:10.3.6.0]
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3739) ~[BUG16619891_1036.jar:10.3.6.0]
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3705) ~[BUG16619891_1036.jar:10.3.6.0]
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) ~[com.bea.core.weblogic.security.identity_1.2.0.0.jar:1.2.0.0]
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120) ~[com.bea.core.weblogic.security.wls_1.0.0.0_6-2-0-0.jar:6.2.0.0]
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2282) ~[BUG16619891_1036.jar:10.3.6.0]
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2181) ~[BUG16619891_1036.jar:10.3.6.0]
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1491) ~[BUG16619891_1036.jar:10.3.6.0]
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256) ~[com.bea.core.weblogic.workmanager_1.11.0.0.jar:1.11.0.0]
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221) ~[com.bea.core.weblogic.workmanager_1.11.0.0.jar:1.11.0.0]

The reponse from the server is ok and the expectation also works but the logs get flooded. Is this perhaps a bug or did we configure something wrong?

release Vert.X Proxy as a Vert.X Module

Extend maven build to enable the creation of the Vert.X Proxy as a stand alone Vert.X Module which can be added to the Vert.X Module Registry (but only once HTTP CONNECT support has been added)

HttpResponse delay applied when serializing expectation

Expected behavior:
response().withDelay(TimeUnit.SECONDS, 10) delays only HTTP response.

Actual behavior:
LogFilter writes warning with delay.

LogFilter.java:83

requestLogger.warn(expectationSerializer.serializeAsJava(new Expectation(entry.getKey(), Times.once()).thenRespond(entry.getValue())))

ExpectationSerializer.java:43

HttpResponse httpResponse = expectation.getHttpResponse();

Expectation.java:30-36

public HttpResponse getHttpResponse() {
    if (httpResponse != null) {
            return httpResponse.applyDelay(); // <--- Delay is applied
        } else {
            return null;
    }
}

QueryString property ignored in expectation to check incoming request

I addition to issue #19 I found out that the queryString property is ignored.
The GET expectation below must only return WSDL if queryString is matched., but even without queryString or wrong queryString it returns WSDL response.

"httpRequest": {
"method": "GET",
"path": "${#Project#PersoonServiceEndpoint}",
"queryString": "(?i)wsdl"
}

Using version 2.6 on JVM 1.6u45

Close ApacheHttpClient

Investigate the following statement:

I didn’t find how to close the HttpClient connection without stopping the server (any hint is really appreciated). I’m not sure but I think this is why the following error is logged on server console:
o java.io.IOException: An existing connection was forcibly closed by the remote host

Clearing expectations doesn't match on query string parameters

Clearing expectations seems to match on method and path, but does not respect the query string parameters. It would be awesome if clear expectations respected all the parameters that are passed in setting up expectations in order to be able to clear particular requests separately.

SaxParseException Content is not allowed in prolog

When i write xpath expression like below i get below exception can you help with this? Thank you.

    availablePort = PortFactory.findFreePort();
    LOG.info("Available Port is {}",availablePort);
    mockServer = startClientAndServer(availablePort);
    FileInputStream fisTargetFile = new FileInputStream((new ClassPathResource("test-files/billsys-rsp/QueryOrder-response.xml")).getFile());
    String mockResponse = IOUtils.toString(fisTargetFile, "UTF-8");       
    String anCondition = "/Envelope/Body/QueryOrders/OrderHistory/AccountNumber='1234'";
    String sfCondition = "/Envelope/Body/QueryOrders/OrderHistory/StatusFilter='ALL'";
    Body body = new StringBody(anCondition+" and "+sfCondition, Type.XPATH);
    HttpRequest withPath = request().withMethod("POST").withPath("/ws/dise3g/services/OrderPort").withBody(body);
    mockServer.when(withPath).respond(response().withStatusCode(200).withBody(mockResponse));
    mockServer.when(request().withMethod("POST").withPath("/BPM/rest/XML")).respond(response().withStatusCode(200).withBody("success"));  
    mockServer.dumpToLog(withPath);

WARN o.m.matchers.XPathStringMatcher - SAXParseException while performing match between [/Envelope/Body/QueryOrders/OrderHistory/AccountNumber='1234' and /Envelope/Body/QueryOrders/OrderHistory/StatusFilter='ALL'] and [/Envelope/Body/QueryOrders/OrderHistory/AccountNumber='1234' and /Envelope/Body/QueryOrders/OrderHistory/StatusFilter='ALL']
org.xml.sax.SAXParseException: Content is not allowed in prolog.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source) ~[xercesImpl-2.9.1.jar:na]
at org.mockserver.matchers.XPathStringMatcher.matches(XPathStringMatcher.java:62) ~[mockserver-core-2.9.jar:na]
at org.mockserver.matchers.XPathStringMatcher.matches(XPathStringMatcher.java:22) ~[mockserver-core-2.9.jar:na]
at org.mockserver.matchers.HttpRequestMatcher.matches(HttpRequestMatcher.java:128) ~[mockserver-core-2.9.jar:na]
at org.mockserver.matchers.HttpRequestMatcher.matches(HttpRequestMatcher.java:99) ~[mockserver-core-2.9.jar:na]
at org.mockserver.mock.Expectation.matches(Expectation.java:49) ~[mockserver-core-2.9.jar:na]
at org.mockserver.mock.MockServerMatcher.dumpToLog(MockServerMatcher.java:96) ~[mockserver-core-2.9.jar:na]
at org.mockserver.mockserver.MockServerHandler.mockResponse(MockServerHandler.java:116) ~[mockserver-netty-2.9.jar:2.9]
at org.mockserver.mockserver.MockServerHandler.channelRead0(MockServerHandler.java:87) ~[mockserver-netty-2.9.jar:2.9]
at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:103) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.channel.DefaultChannelHandlerContext.invokeChannelRead(DefaultChannelHandlerContext.java:338) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.channel.DefaultChannelHandlerContext.fireChannelRead(DefaultChannelHandlerContext.java:324) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:153) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:148) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.channel.DefaultChannelHandlerContext.invokeChannelRead(DefaultChannelHandlerContext.java:338) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.channel.DefaultChannelHandlerContext.fireChannelRead(DefaultChannelHandlerContext.java:324) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:785) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:132) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:485) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:452) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:346) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101) ~[netty-all-4.0.15.Final.jar:4.0.15.Final]
at java.lang.Thread.run(Thread.java:724) ~[na:1.7.0_25]

NPE when creating an expectation which does not return response

When using mockserver-netty to create tests which does not return response I got NPE.
Test sample:

import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockserver.integration.ClientAndServer;
import org.springframework.web.client.RestTemplate;

public class SampleTest {
    private int port = 9999;

    private ClientAndServer mockServer;
    private RestTemplate restTemplate;

    @Before
    public void setup() throws Exception {
        mockServer = startClientAndServer(port);

        restTemplate = new RestTemplate();
    }

    @After
    public void teardown() throws Exception {
        mockServer.stop();
    }

    @Test
    public void testEmptyResponse() {

        String request = "dummyRequestBody";
        mockServer
                .when(request().withMethod("POST").withPath("/foo")
                        .withBody(request))
                .respond(
                        response().withStatusCode(200));

        String url = "http://127.0.0.1:" + port + "/foo";
        restTemplate.postForEntity(url, request, Void.class);

    }
}

Whenever I execute this test I got:

2014-05-15 17:01:37,737 WARN o.m.m.MockServerHandler Exception caught by MockServer handler closing pipeline
java.lang.NullPointerException: null
    at java.lang.String.<init>(String.java:556) ~[na:1.7.0_55]
    at org.mockserver.model.HttpResponse.getBody(HttpResponse.java:62) ~[mockserver-core-2.9.jar:na]
    at org.mockserver.mappers.MockServerToNettyResponseMapper.mapMockServerResponseToNettyResponse(MockServerToNettyResponseMapper.java:21) ~[mockserver-netty-2.9.jar:na]
    at org.mockserver.mockserver.MockServerHandler.mockResponse(MockServerHandler.java:148) ~[mockserver-netty-2.9.jar:2.9]
    at org.mockserver.mockserver.MockServerHandler.channelRead0(MockServerHandler.java:87) ~[mockserver-netty-2.9.jar:2.9]
    at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:103) ~[netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.channel.DefaultChannelHandlerContext.invokeChannelRead(DefaultChannelHandlerContext.java:338) [netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.channel.DefaultChannelHandlerContext.fireChannelRead(DefaultChannelHandlerContext.java:324) [netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:153) [netty-codec-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:148) [netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.channel.DefaultChannelHandlerContext.invokeChannelRead(DefaultChannelHandlerContext.java:338) [netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.channel.DefaultChannelHandlerContext.fireChannelRead(DefaultChannelHandlerContext.java:324) [netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:785) [netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:132) [netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:485) [netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:452) [netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:346) [netty-transport-4.0.15.Final.jar:4.0.15.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101) [netty-common-4.0.15.Final.jar:4.0.15.Final]
    at java.lang.Thread.run(Thread.java:745) [na:1.7.0_55]

Setting delay delays JSON response

Hi James,

I am running into an issue with setting the timeout when creating an expectation.

When I specify a delay of 5 seconds, the JSON call for creating an expectation takes 5 seconds to return. When I specify a delay of 15 seconds, it will take 15 seconds. It looks as the delay is immediatly applied to the JSON call itself.

Jeroen

Proxy as default behaviour when no expectations set

Hi,

Thanks for this great tool, it works like a charm! We use MockServer extensively for testing our webservices with mocked back-ends and are very happy with it.

We have some struggle however because after deployment our webservices cannot easily switch between mock and real backend. So I was thinking to maybe use Apache to route between /mockserver and the backend services, but that would involve a lot of configuration for each service.

I read on the mock-server.com that MockServer also supports basic proxying functionality. So ideally I would like MockServer to act as a proxy and let it route all requests to the backend webservices, based on some default expectation. Then at some point when I upload short-living expectations, MockServer should change it behaviour from proxying to mocking, and after the count of remainingTimes has passed it should return to proxying behaviour.

Do you think that would be possible with Mock Server?

404 response with PUT method on root resource (Java 1.6u45)

When running version 2.5 and 2.6 standalone or as war on weblogic I;m getting a 404 reponse when sending (PUT) a new expectation to mockserver.

I'm running the standalone version (JAR w/ Dependencies) on Java 1.6 update 45 on serverPort 8080. When sending JSON request (PUT method) to resource / it returns the 404 error, but a 201 is expected.

Is this changed in the new API? Should I use a different resource url?

mockserver-war file not works in Wildfly

Hello,

I really love mock-server project, in fact currently I am developing an Arquillian extension for mock-server. But I have found one problem when I try to deploy mockserver-war-2.10 to wildfly 8.0. When I deploy the war file inside Wildfly next exception is thrown:

23:39:44,968 INFO  [org.jboss.weld.deployer] (MSC service thread 1-3) JBAS016008: Starting weld service for deployment mockserver-war-2.10.war
23:39:45,042 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit."mockserver-war-2.10.war".WeldStartService: org.jboss.msc.service.StartException in service jboss.deployment.unit."mockserver-war-2.10.war".WeldStartService: Failed to start service
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.0.Final.jar:1.2.0.Final]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0]
    at java.lang.Thread.run(Thread.java:744) [rt.jar:1.8.0]
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type Set<Service> with qualifiers @Default
  at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] @Inject com.google.common.util.concurrent.ServiceManager(Set<Service>)
  at com.google.common.util.concurrent.ServiceManager.<init>(ServiceManager.java:0)

    at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:368)
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:289)
    at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:135)
    at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:166)
    at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:514)
    at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:68)
    at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:66)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [rt.jar:1.8.0]
    ... 3 more

23:39:45,045 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 33) JBAS014613: Operation ("deploy") failed - address: ([("deployment" => "mockserver-war-2.10.war")]) - failure description: {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"mockserver-war-2.10.war\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"mockserver-war-2.10.war\".WeldStartService: Failed to start service
    Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type Set<Service> with qualifiers @Default
  at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] @Inject com.google.common.util.concurrent.ServiceManager(Set<Service>)
  at com.google.common.util.concurrent.ServiceManager.<init>(ServiceManager.java:0)
"}}
23:39:45,045 ERROR [org.jboss.as.server] (management-handler-thread - 33) JBAS015870: Deploy of deployment "mockserver-war-2.10.war" was rolled back with the following failure message:
{"JBAS014671: Failed services" => {"jboss.deployment.unit.\"mockserver-war-2.10.war\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"mockserver-war-2.10.war\".WeldStartService: Failed to start service
    Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type Set<Service> with qualifiers @Default
  at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] @Inject com.google.common.util.concurrent.ServiceManager(Set<Service>)
  at com.google.common.util.concurrent.ServiceManager.<init>(ServiceManager.java:0)
"}}

Any idea of what it is happening?

Thank you so much for your help,
Alex.

Support Optionally Mocking Response or Forward Request

Request from Wilfred van der Deijl:

"Hi James. We've been using MockServer at a large client in the Netherlands for mocking (soap) web services when unit testing compound services that are supposed to invoke other services. This works great and we love the mechanism of selecting certain requests eligible for mocking. Developers run with a local MockServer, but testers want to use the central Service Bus that points to a single central MockServer installation. The configure this with a number of REST calls prior to performing their (soapUI) tests. This works fine but we want to take the next step in testing web userinterface that invoke (soap) services. Sometimes testers want to run the UI against "real" services and sometimes against MockServer. We're looking for a way to change this dynamically and preferably per request. I've been thinking about setting up MockProxy and have it forward certain requests to MockServer and certain requests to the "real" server. We could use the already great system of selecting requests. The only thing is that MockProxy doesn't support forwarding/rewriting requests to other origin servers than what was requested by the client. I hope I could explain what we're looking for. Is this something that is on your roadmap or are you willing to accept this as a contribution from our side?"

Response:

"Hi Wilfred, I'm happy to look into this as there is a proxy in the MockServer that is currently used to record requests while making requests to a real endpoint. I'm fairly sure I can connect the two parts together. To be honest I'm just had a quick look and it looks like a fairly straight forward addition if done in the correct way. I'll see what I can do I might be able to have this completed and released by the end of the weekend. If not mid next week should be doable."

Removing specific expectations

Hi,

I have a question concerning the removing of specific expectations. Is it possible to remove a single expectation for a specific path?

For example: I have set an expectation for path /test with an XPath body match on //test=1. I have set a second expectation for path /test with an XPath body match on //test=2. Is it possible to remove the first expectation without removing the second one, even if no message has been received by the mock server?

Jeroen

Clear operation doesn't seem to work (SoapUI Rest call)

In the new 2.6 version I can't clear expectations.

I'm setting up an expectation for some WSDLs and Mock responses, but when a test fails I want to clear the expectations. When sending a put request to the /clear resources the expectations are not cleared.

First I setting up this GET expectation:

PUT http://localhost:8401/expectation HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/json
Content-Length: 6982
Host: localhost:8401
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

{
"httpRequest": {
"method": "GET",
"path": "/elementair/PersoonService/1.1",
"queryString": "(?i)wsdl"
},
"httpResponse": {
"statusCode": 200,
"headers": [
{
"name": "Content-Type",
"values": ["text/xml; charset=utf-8"]
}
],
"body": " "
},
"times": {
"unlimited": true
}
}

To clear the expectation I use:

PUT http://localhost:8401/clear HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/json;charset=UTF-8
Content-Length: 76
Host: localhost:8401
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

{
"httpRequest": {
"method": "GET"
}
}

The clear operation returns with a 202 Accepted.

Thanks in advance,
Robert

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.