转载自: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.  }

最新文章

  1. 使用最快速的方式激活windows10专业版
  2. iOS开发 适配iOS10以及Xcode8
  3. 简单工程使用sbt公共库(sbt-assembly)
  4. PHP使用CURL上传|下载文件
  5. js init : function ()
  6. 深入学习netty系列(1)
  7. Date Format, 时间戳格式化
  8. I&#39;m back
  9. Fancytree Javascript Tree的入门使用
  10. html查看器android
  11. Java并发编程之并发容器
  12. Windows 10 Version 1803 (Updated March 2018) MSDN 镜像下载
  13. java-Collection集合、List集合、Vector集合和迭代器Iterator、ListIterator的使用
  14. 关于音频总线IIS的学习---Verilog
  15. js五道经典练习题--第五道成绩列表
  16. Wifi小车资料
  17. android中的ellipsize
  18. Mac OS下Appium环境搭建及Genymotion模拟器安装
  19. 成都Uber优步司机奖励政策(2月16日)
  20. BZOJ5339:[TJOI2018]教科书般的亵渎——题解

热门文章

  1. Extract Dataset
  2. go语言中container容器数据结构heap、list、ring
  3. ABP框架使用Mysql数据库
  4. spring boot (一): Hello World
  5. Linux命令大全完整版
  6. java性能优化之for循环
  7. Python GUI中 text框里实时输出
  8. error C4996: &#39;GetVersionExW&#39;: 被声明为已否决
  9. Spring访问数据库(方式上跟HQL类似,每行记录映射一个实体类)
  10. gensim_主题提取