项目引入WireMock,模拟数据。

1、首先访问 http://wiremock.org/docs/running-standalone/ ,下载jar包,并在本地指定端口号,将其启动起来:

java -jar wiremock-standalone-2.23.2.jar --port 9999

2、在项目的pom依赖中添加:

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

3、在项目中创建WireMock的启动文件:

import com.github.tomakehurst.wiremock.client.MappingBuilder;
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;
import static com.github.tomakehurst.wiremock.client.WireMock.*;

public class MockServer {
    public static void main(String[] args) throws IOException {
       configureFor(9999);
        removeAllMappings();
        mock("/url","data");
    }
    private static void mock(String url, String file) throws IOException {
        ClassPathResource resource = new ClassPathResource("mock/response/"+file+".txt");
        String content = StringUtils.join(FileUtils.readLines(resource.getFile(),"UTF-8").toArray(),"\n");
        stubFor(WireMock.get(urlPathEqualTo(url)).willReturn(aResponse().withBody(content)));
    }
}

说明:这里将接口的响应数据写在了项目中的文件夹里,根据请求的接口匹配对应的请求数据。


63 Clicks !

发表评论

电子邮件地址不会被公开。