转载自:https://blog.csdn.net/heymysweetheart/article/details/52227379;(注,这个不是很符合我的要求,它主要的作用是可以通过简单的代码就能filter对方的请求options,然后做出对应的响应;而我需要的是一个能够开启为http服务端来测试客户端发来的http请求的工具,然后顺便看到了这篇感觉以后可能也会用到)

前言

进行单元测试时,必须要mock掉第三方的依赖调用,而mockserver提供了足够的api来支持这种http的mock,现在简单介绍如何使用mockserver进行http接口mock。

依赖

  • mockserver依赖

    
    
    1. <dependency>
    2.  <groupId>org.mock-server</groupId>
    3.  <artifactId>mockserver-netty</artifactId>
    4.  <version>3.10.4</version>
    5. </dependency>
  • httpclient依赖

  1. <dependency>
  2.  <groupId>org.apache.httpcomponents</groupId>
  3.  <artifactId>httpclient</artifactId>
  4.  <version>4.3.3</version>
  5. </dependency>
  6. <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
  7. <dependency>
  8.  <groupId>org.apache.httpcomponents</groupId>
  9.  <artifactId>httpcore</artifactId>
  10.  <version>4.3.2</version>
  11. </dependency>

httpclient的版本可能会出现不一致的情况,抛出异常,以上的这个版本匹配是没有异常的组合。

举例


  1. package com.yuliang.dubbo.service;
  2. import org.apache.http.client.methods.CloseableHttpResponse;
  3. import org.apache.http.client.methods.HttpGet;
  4. import org.apache.http.impl.client.CloseableHttpClient;
  5. import org.apache.http.impl.client.HttpClients;
  6. import org.junit.Rule;
  7. import org.junit.Test;
  8. import org.mockserver.client.server.MockServerClient;
  9. import org.mockserver.junit.MockServerRule;
  10. import java.io.BufferedReader;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.io.InputStreamReader;
  14. import static org.hamcrest.CoreMatchers.equalTo;
  15. import static org.hamcrest.MatcherAssert.assertThat;
  16. import static org.mockserver.model.HttpRequest.request;
  17. import static org.mockserver.model.HttpResponse.response;
  18. /**
  19. * Created by leo on 16/8/16.
  20. */
  21. public class MockServerTest {
  22.  @Rule
  23.  public MockServerRule server = new MockServerRule(this, 5000);
  24.  @Test
  25.  public void testMockServer() throws IOException {
  26.  MockServerClient mockClient = new MockServerClient("localhost", 5000);
  27.  String expected = "{ message: 'incorrect username and password combination' }";
  28. mockClient.when(
  29. request()
  30.  .withPath("/hello/John")
  31.  .withMethod("GET")
  32. // .withHeader(new Header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN))
  33. // .withQueryStringParameter(new Parameter("my-token", "12345"))
  34.  ).respond(
  35. response()
  36.  .withStatusCode(200)
  37.  .withBody(expected)
  38.  );
  39.  CloseableHttpClient client = HttpClients.createDefault();
  40.  HttpGet httpGet = new HttpGet("http://localhost:5000/hello/John");
  41.  CloseableHttpResponse response = client.execute(httpGet);
  42.  //验证输出是否是正确
  43.  InputStream content = response.getEntity().getContent();
  44.  InputStreamReader inputStreamReader = new InputStreamReader(content);
  45.  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  46.  String responseText = bufferedReader.readLine();
  47. assertThat(responseText, equalTo(expected));
  48.  }
  49. }
  • mock http post请求

    
    
    1. @Test
    2.  public void testPostMockServer() throws IOException {
    3.  MockServerClient mockClient = new MockServerClient("localhost", 5000);
    4.  String expected = "You have logged in successfully.";
    5. mockClient.when(
    6. request()
    7.  .withPath("/hello/John")
    8.  .withMethod("POST")
    9.  .withHeader(new Header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN))
    10. // .withQueryStringParameter(new Parameter("my-token", "12345"))
    11.  .withBody("username=foo&password=123456")
    12.  ).respond(
    13. response()
    14.  .withStatusCode(200)
    15.  .withBody(expected)
    16.  );
    17.  CloseableHttpClient client = HttpClients.createDefault();
    18.  HttpPost httpPost = new HttpPost("http://localhost:5000/hello/John");
    19. httpPost.addHeader("Accept", "text/plain");
    20.  ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    21. nameValuePairs.add(new BasicNameValuePair("username", "foo"));
    22. nameValuePairs.add(new BasicNameValuePair("password", "123456"));
    23. httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    24.  CloseableHttpResponse response = client.execute(httpPost);
    25.  //验证输出是否是正确
    26.  InputStream content = response.getEntity().getContent();
    27.  InputStreamReader inputStreamReader = new InputStreamReader(content);
    28.  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    29.  String responseText = bufferedReader.readLine();
    30. assertThat(responseText, equalTo(expected));
    31.  }

使用mockserver来进行http接口mock的更多相关文章

  1. 使用electron开发一个h5的客户端应用创建http服务模拟后台接口mock

    使用electron开发一个h5的客户端应用创建http服务模拟后端接口mock 在上一篇<electron快速开始>里讲述了如何快速的开始一个electron的应用程序,既然electr ...

  2. RPC接口mock测试

    转载:http://blog.csdn.net/ronghuanye/article/details/71124127 1        简介 Dubbo目前的应用已经越来越广泛.或者基于Dubbo二 ...

  3. rpc接口mock平台

    转载:http://blog.csdn.net/ronghuanye/article/details/71124320 1.简介 平台采用struts.spring.mybatis框架开发设计,主要用 ...

  4. anyproxy学习2-rule模块实现接口mock功能

    前言 AnyProxy不仅仅可以抓包,还可以拦截请求并修改服务端响应,实现接口mock功能. 面试时候经常会问到第三方支付如何测试这种,如果对接的第三方没提供测试环境,那么就需要搭建一个mock服务器 ...

  5. 努力一周,开源一个超好用的接口Mock工具——Msw-Tools

    作为一名前端开发,是不是总有这样的体验:基础功能逻辑和页面UI开发很快速,本来可以提前完成,但是接口数据联调很费劲,耗时又耗力,有时为了保证进度还不得不加加班. 为了摆脱这种痛苦,经过一周的努力,从零 ...

  6. RAP 接口Mock示例

    前后端分离式开发的思考 目前大部分公司都实行了前后端分离开发.然而在项目开发过程当中,经常会遇到以下几个尴尬的场景: 1.前端开发依赖于后端接口数据,需要与后端接口联调才能获得数据展示,从而拖慢了开发 ...

  7. Doclever 接口mock 操作

    查看 接口项目mock 查看说明 假设 本机项目路径为  http://localhost:8080 >> 启动 node node net.js http://org.my.com/mo ...

  8. fiddler实现后端接口 mock(不需要修改开发代码)

    转载:http://blog.csdn.net/huazhongkejidaxuezpp/article/details/50435552 步骤   1.  获取 接口 定义(接口返回的json串) ...

  9. SpringBoot开发mockserver及生成swagger接口文档

    通过springboot开发mock server,包含get及post接口,用于练习接口自动化及jmeter很方便 当然,也为后面jenkins持续集成做基础(开发push代码后  → jenkin ...

随机推荐

  1. java实现rabbitMQ延时队列详解以及spring-rabbit整合教程

    在实际的业务中我们会遇见生产者产生的消息,不立即消费,而是延时一段时间在消费.RabbitMQ本身没有直接支持延迟队列功能,但是我们可以根据其特性Per-Queue Message TTL和 Dead ...

  2. ABAP中不修改内表参照的结构,给内表/结构体增加字段

    Situation: DATA:       itab  TYPE STANDARD TABLE OF zsrsodtla_stru1,      wa_itab TYPE zsrsodtla_str ...

  3. Java 对象 引用,equal == string

    以前确实一直没注意这个概念,这次看了帖子才知道. 转载于:https://zwmf.iteye.com/blog/1738574 Java对象及其引用 关于对象与引用之间的一些基本概念. 初学Java ...

  4. Oauth2.0 认证的Web api例子

    Oauth2.0的解释 OAuth(开放授权)是一个开放标准,允许用户授权第三方移动应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容.OA ...

  5. Mysql数据库(一)

    一 什么是数据库 一般来说,所有的数据都要存储在硬盘中,为了方便对这些数据的管理因此就出现了例如MySQL SQLserver oracle等数据库管理软件. 数据库中的数据按一定的数据模型组织.描述 ...

  6. 整站变灰CSS代码

    * { filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=1); -webkit-filter: grayscale(100% ...

  7. java传统web项目添加maven管理jar包,log4j无法正常输出日志

    本文适合1年以上编程基础的开发人员阅读,非技术创新,可作为故障排除实录参考/收藏. 背景 笔者最近在给公司一个老的web项目改造升级,项目使用springmvc+mybatis,由于项目比较久远,没有 ...

  8. Svn Server 强制提交者输入注释信息

    目的:在项目开发过程中,强制团队成员必须在提交前写上注释 环境简述:SVN服务器:Windows Server 2008 SVN版本:VisualSVN Ltd.  2.7.5 操作方法:在SVN的R ...

  9. XHR的对象及用法

    function  createXHR(){         //检测原生XHR对象是否存在,如果存在刚返回它的新实例:     //如果不存在,则检测ActiveX对象;     //如果两个都不存 ...

  10. sqlserver 2008 还原数据库时,提示有用户正在使用,无法取得使用占有权

    sqlserver 2008 还原数据库时,提示有用户正在使用,无法取得使用占有权 这个时候,只需要把数据库分离出去,再附加,然后还原即可 分离数据库的时候能看到有几个数据连接