I have been using Wiremock version of standalone, the code used in the simple encapsulation of the HTTP request to use, later looked at the Wiremock own client use is also good, also support remote access, so recommend to everyone
Using local Wiremock
A stub's demo
- First, add a good dependency to the POM
<dependency> <groupId>Com.github.tomakehurst</groupId> <artifactid>Wiremock</artifactid> <version>1.56</version> <!--Include Everything below here if you have dependency conflicts -- <classifier>Standalone</classifier> <exclusions> <exclusion> <groupId>Org.mortbay.jetty</groupId> <artifactid>Jetty</artifactid> </exclusion> <exclusion> <groupId>Com.google.guava</groupId> <artifactid>Guava</artifactid> </exclusion> <exclusion> <groupId>Com.fasterxml.jackson.core</groupId> <artifactid>Jackson-core</artifactid> </exclusion> <exclusion> <groupId>Com.fasterxml.jackson.core</groupId> <artifactid>Jackson-annotations</artifactid> </exclusion> <exclusion> <groupId>Com.fasterxml.jackson.core</groupId> <artifactid>Jackson-databind</artifactid> </exclusion> <exclusion> <groupId>Org.apache.httpcomponents</groupId> <artifactid>HttpClient</artifactid> </exclusion> <exclusion> <groupId>Org.skyscreamer</groupId> <artifactid>Jsonassert</artifactid> </exclusion> <exclusion> <groupId>Xmlunit</groupId> <artifactid>Xmlunit</artifactid> </exclusion> <exclusion> <groupId>Com.jayway.jsonpath</groupId> <artifactid>Json-path</artifactid> </exclusion> <exclusion> <groupId>Net.sf.jopt-simple</groupId> <artifactid>Jopt-simple</artifactid> </exclusion> </exclusions></Dependency>
- In the Java file, you need to import the Wiremocker server, client, config three classes
import com.github.tomakehurst.wiremock.WireMockServer;import static com.github.tomakehurst.wiremock.client.WireMock.*;import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
- And here is TestNG's demo.
@BeforeClass Public void setUp() throws FileNotFoundException, IOException{//Configure local PortWiremock.configurefor (9090); Wiremockserver =NewWiremockserver (Wiremockconfig (). Port (9090)); Log.info ("START Wiremock");//StartWiremockserver.start (); }@AfterClass Public void tearDown() throws FileNotFoundException, IOException{//Stop the mockWiremockserver.stop (); }@Test Public void testformock() {//Configure RuleStubfor (Post (Urlequalto ("/api/add"). Willreturn (Aresponse (). Withstatus ( $). Withbody ("Hzmali")));//Write your own post methodString Response=httputil.post ("Http://127.0.0.1:9090/api/add",""); Log.info ("GET RESP:"+response);//CheckAssert.asserttrue (Response.contains ("Hzmali")); }}
The results are successful, the logs are normal
[INFO ]11:52:54, [Class]MockCliTest, [Method]setUp, START WIREMOCK[INFO ]11:52:54, [Class]MockCliTest, [Method]testForMock, GET RESP:hzmaliPASSED: testForMock
The rule setting here
stubFor(post(urlEqualTo("/api/add")) .willReturn(aResponse().withStatus(200).withBody("hzmali")));
Equivalent to the usual JSON configuration
"requestt" : { "url""/api/add", "method""POST" }, "response" : { "status"200, "body""hzmali" }
More advanced stub rules such as:
Regular matching of URLs:
stubFor(put(urlMatching("/thing/matching/[0-9]+")) .willReturn(aResponse().withStatus(200)));stubFor(put(urlMatching("/thing/matching/.*")) .willReturn(aResponse().withStatus(200)));
Match of the header and body of request
stubfor (Post (Urlequalto ( "/with/headers" )) . Withheader ( "Content-type" , Equalto ( "Text/xml" ). Withheader ( "Accept" , matching ( "text/.*" ). Withheader ( "ETag" , notmatching ( "abcd.*" ). Withheader ( "X-custom-header" , containing ()". Willreturn (Aresponse (). Withstatus (200 )); Stubfor (Post ( Urlequalto ( "/with/json/body" )). Withrequestbody (Equaltojson " {\ "Housenumber\": 4, \ "postcode\": \ "N1 1zz\"} "). Willreturn (Aresponse (). Withstatus (200 )));
More stub matching parameters, specifying return files etc. view official manual stub
Accessing the remote Wiremock
Unit testing generally like the above as a local wiremock to mock, interface test Wiremock is generally built on another machine, so in the automated interface testing, with local calls differ
To make changes based on the demo above, just tell the client where the mock is.
Wiremock.configurefor ("192.168.231.131", 8080);
There is no need to create a local wiremock, the address of the sending request must be changed to be consistent with the purpose Wiremock
@BeforeClass Public void setUp() throws FileNotFoundException, IOException{Wiremock.configurefor ("192.168.231.131",8080);//wiremockserver = new Wiremockserver (Wiremockconfig ()); //log.info ("START wiremock"); //wiremockserver.start ();}@AfterClass Public void tearDown() throws FileNotFoundException, IOException{//wiremockserver.stop ();}
The Wiremock log also shows that there are set rule and match on the
-- -- One A: the:06.438Received request to/mappings/NewWith body {"Request": {"url":"/api/add","Method":"POST"},"Response": {"Status": $,"Body":"Hzmali"}} -- -- One A: the:06.519ReceivedRequest:POST/api/Add http/1.1user-Agent:Jakarta commons-httpclient/3.0. 1Host: 192.168. 231. 131:8080content-Length: 0 -- -- One A: the:06.519RequestReceived:POST/api/Add http/1.1user-Agent:Jakarta commons-httpclient/3.0. 1Host: 192.168. 231. 131:8080content-Length: 0
Postscript
The newest Wiremock official homepage is very conscientious recommend some kind of mock tool
Betamax
Rest-driver
Mockserver
Moco
Betamax: To be used with JUnit, annotated style, no standalone version no love, the page is too loud look for a while to turn off
Rest-driver: Mainly used for testing restful clients and services, so it is divided into client-driver,server-driver, mainly used for single measurement
, where Server-driver encapsulates the restful request and response, and the request-sending tool for the interface test is also good for
Moco: A framework/tool/library that can easily build a test server, support sockets, write in Chinese, grammar and commands are simple
Mockserver: Features that are more powerful than wiremock, support functions and invocation methods The most of these tools, support Maven, Java API, standalone, node. JS, Docker images, and other ways to use.
Among these features are the following:
Mockserver would play expectationsinchThe exactOrderThey is setup. forExampleifAn expectation A isSetup toResponse (or forward)3Times ThenExpectation B isSetup toResponse (or forward)2Times forThe same request Mockserver would response (or forward)inchThe followingOrderA, A, a, B, B.
Feel a bit, for some scenarios (such as an internal logic needs to trigger failure retry or re-connect), the first call to the A interface to return the exception, the second call to the A interface returned to normal, for the call Towners said that because the internal invocation of the interface is not visible to the outside world, generally let the first return failure is very easy, But there is no good way to control when to let the second return to the exception, then mockserver this by the timing of the return of the very cock bombing days, have time to study
Using the Wiremock library in your project