1. 程式人生 > >wireMock快速偽造restful服務

wireMock快速偽造restful服務

service file png frame das 之前 order moc pid

官網地址:http://wiremock.org/

Jar下載:http://repo1.maven.org/maven2/com/github/tomakehurst/wiremock/1.57/wiremock-1.57-standalone.jar

下載wiremock jar工具

jar下載完畢後,啟動jar,

java -jar wiremock-1.57-standalone.jar –port 9999 --verbose

技術分享圖片

配合springboot項目,能夠隨時更新mockservice

相關依賴:

        <dependency>
            <groupId>com.github.tomakehurst</groupId>
            <artifactId>wiremock</artifactId>
        </dependency>

新建mock服務:

package com.nxz.wiremock;

import com.github.tomakehurst.wiremock.client.WireMock;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

/**
 * 啟動mockserver服務
 
*/ public class MockServer { public static void main(String[] args) throws IOException { WireMock.configureFor(9999);//指定端口 WireMock.removeAllMappings();//清空之前的配置 //每調用一次mock方法,就代表提供了一個mockservice接口
     mock(
"/order/1", "01.txt"
); mock("/order/2", "02.txt"
); }
private static void mock(String url, String file) throws IOException {
    //mock\\response\\+file 這裏指定的是返回的json數據 ClassPathResource resource
= new ClassPathResource("mock\\response\\" + file); String content = StringUtils.join(FileUtils.readLines(resource.getFile(), "UTF-8").toArray()); WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo(url)) .willReturn(WireMock.aResponse().withBody(content).withStatus(200))); } }

模擬返回數據:

{
    "aaa":1,
    "type":"a"
}

wireMock快速偽造restful服務