木心

毕竟几人真得鹿,不知终日梦为鱼

导航

使用WireMock伪造REST服务

在真正的rest api服务还没有写好之前,为了方便前端测试调用,后端可以写个服务,伪造rest服务(写假数据)

 

1、官网: http://wiremock.org/

下载可执行jar:http://wiremock.org/docs/running-standalone/

 

2、java -jar启动服务

 

3、springboot的pom文件引入依赖

<!-- WireMock -->
<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock</artifactId>
</dependency>

<!-- httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

 

4、测试代码

package com.imooc.wiremock;

import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.ClassPathResource;

import com.github.tomakehurst.wiremock.client.WireMock;

/**
 * @author oy
 * @date 2019年6月24日 下午11:13:12
 * @version 1.0.0
 */
public class MockServer {
    public static void main(String[] args) throws IOException {
        WireMock.configureFor(8082);
        WireMock.removeAllMappings();
        
        WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo("/user/1")).willReturn(
                WireMock.aResponse().withBody("{\"id\":1}").withStatus(200)));
        
        mock("/user/2", "01");
    }
    
    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");
        WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo(url)).willReturn(WireMock.aResponse().withBody(content).withStatus(200)));
    }
}

  

 

 测试结果:

  

  

posted on 2019-06-23 23:52  wenbin_ouyang  阅读(350)  评论(0编辑  收藏  举报