zoukankan      html  css  js  c++  java
  • 使用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(), "
    ");
            WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo(url)).willReturn(WireMock.aResponse().withBody(content).withStatus(200)));
        }
    }

      

     测试结果:

      

      

  • 相关阅读:
    Confluence 6 连接到一个 LDAP 目录
    Confluence 6 LDAP 成员结构设置
    Confluence 6 LDAP 用户组结构设置
    Confluence 6 LDAP 用户结构设置
    Confluence 6 LDAP 高级设置
    Confluence 6 自动添加用户到用户组
    Confluence 6 权限设置
    一个小白的测试环境docker化之路
    客户端SDK测试思路
    限时购校验小工具&dubbo异步调用实现限
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/11074965.html
Copyright © 2011-2022 走看看