美文网首页
WireMock实战-1

WireMock实战-1

作者: 聆世冷暖 | 来源:发表于2018-11-22 22:48 被阅读0次

    一.简介

    1.是什么
    WireMock是一个基于http api的模拟器。有些人可能认为它是服务虚拟化工具或模拟服务器。
    它使您能够在依赖的API不存在或不完整时保持高效。它的构建速度很快,可以将构建时间从几个小时减少到几分钟。

    2.能做什么
    可以做单元测试,独立的 JAR 可以做前后端分离开发&联调使用.

    二.版本简介

    WireMock有两种版本:

    • 一个标准的JAR只包含WireMock;
    • 一个独立的JAR包含WireMock及其所有依赖项.

    在某些情况下 WireMock 可能会与某些代码中的包产生冲突.
    独立的 JAR 所依赖的包被隐藏在包中,与项目本身的代码相对独立.
    说白了,标准的 WireMock 是与测试代码耦合在一起的运行在同一个进程同一个JVM 中.独立的WireMock 包是运行在另外的进程中,也是独立的 JVM.

    目前,建议您使用独立JAR作为Spring引导项目的依赖项。这避免了关于 Jetty 版本的冲突.

    三. MAVEN

    要将标准WireMock JAR作为项目依赖项添加到POM的依赖项部分:

    <dependency>
        <groupId>com.github.tomakehurst</groupId>
        <artifactId>wiremock</artifactId>
        <version>2.19.0</version>
        <scope>test</scope>
    </dependency>
    

    或使用独立JAR:

    <dependency>
        <groupId>com.github.tomakehurst</groupId>
        <artifactId>wiremock-standalone</artifactId>
        <version>2.19.0</version>
    </dependency>
    

    四.JUnit 4.x 用法

    JUnit规则提供了在测试用例中包含WireMock的方便方法。它为您处理生命周期,在每个测试方法之前启动服务器,然后停止。

    1.基本用法
    在默认的端口(8080)启用WireMock.

    @Rule
    public WireMockRule wireMockRule = new WireMockRule();
    

    WireMockRule 通过构造函数来设置.设置项通过Options实例来创建:

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(options().port(8888).httpsPort(8889));
    

    详细配置信息[http://wiremock.org/docs/configuration/]

    2.不匹配的请求
    JUnit规则将验证在测试用例过程中接收到的所有请求都是由配置的存根(而不是默认的404)提供服务的。如果没有抛出验证异常,则测试失败。这个行为可以通过传递一个额外的构造函数标志来禁用:

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(options().port(8888), false);
    

    3.其他@Rule配置

    @ClassRule
    public static WireMockClassRule wireMockRule = new WireMockClassRule(8089);
    
    @Rule
    public WireMockClassRule instanceRule = wireMockRule;
    

    4.从规则访问 stub & 验证DSL
    除了WireMock类上的静态方法外,还可以通过规则对象直接配置stubs 。
    这样做有两个好处:
    1)它更快,因为它避免了通过HTTP发送命令;
    2)如果你想模拟多个服务,你可以为每个服务声明一个规则,但不需要为每个服务创建一个客户端对象。

    @Rule
    public WireMockRule service1 = new WireMockRule(8081);
    
    @Rule
    public WireMockRule service2 = new WireMockRule(8082);
    
    @Test
    public void bothServicesDoStuff() {
        service1.stubFor(get(urlEqualTo("/blah")).....);
        service2.stubFor(post(urlEqualTo("/blap")).....);
    
        ...
    }
    

    五.JUnit 4.x 实战

    测试标准的 WireMock 包,原理是启动测试模块之前先启动一个内置的 MockServer.

    写个 Service 要调用远程服务,地址为 http://127.0.0.1:8080/hello

    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Service;
    import org.springframework.web.client.RestTemplate;
    
    /**
     * <p>
     * 创建时间为 下午2:52-2018/11/21
     * 项目名称 SpringBootWireMock
     * </p>
     *
     * @author shao
     * @version 0.0.1
     * @since 0.0.1
     */
    
    
    @Service
    public class RemoteService {
    
        private RestTemplate restTemplate = new RestTemplate();
    
        public String access(){
            ResponseEntity<String> result = restTemplate.getForEntity("http://127.0.0.1:8080/hello", String.class);
            System.out.println(result);
            return result.getBody();
        }
    
    }
    
    

    编写单元测试

    import com.github.tomakehurst.wiremock.junit.WireMockClassRule;
    import org.junit.ClassRule;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
    import static com.github.tomakehurst.wiremock.client.WireMock.get;
    import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
    import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
    
    
    /**
     * <p>
     * 创建时间为 下午2:53-2018/11/21
     * 项目名称 SpringBootWireMock
     * </p>
     *
     * @author shao
     * @version 0.0.1
     * @since 0.0.1
     */
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class RemoteServiceTest {
    
        // Start WireMock on some dynamic port
        // for some reason `dynamicPort()` is not working properly
        @ClassRule
        public static WireMockClassRule wiremock = new WireMockClassRule(options().port(8080));
        // A service that calls out over HTTP to localhost:${wiremock.port}
        @Autowired
        private RemoteService service;
    
        @Test
        public void access() throws Exception {
            // Stubbing WireMock
            wiremock.stubFor(get(urlEqualTo("/hello"))
                .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello World!")));
            // We're asserting if WireMock responded properly
            System.out.println(service.access());
    
        }
    
    }
    

    测试结果

    2018-11-21 16:10:32.096  INFO 2105 --- [           main] c.h.s.service.RemoteServiceTest          : Started RemoteServiceTest in 7.554 seconds (JVM running for 12.989)
    2018-11-21 16:10:32.662  INFO 2105 --- [qtp609887969-18] o.e.j.s.handler.ContextHandler.ROOT      : RequestHandlerClass from context returned com.github.tomakehurst.wiremock.http.StubRequestHandler. Normalized mapped under returned 'null'
    <200,Hello World!,{Content-Type=[text/plain], Matched-Stub-Id=[a00a6350-bf66-4d89-969d-c5a8cb49c3c0], Vary=[Accept-Encoding, User-Agent], Transfer-Encoding=[chunked], Server=[Jetty(9.4.12.v20180830)]}>
    Hello World!
    2018-11-21 16:10:33.013  INFO 2105 --- [           main] o.e.jetty.server.AbstractConnector       : Stopped NetworkTrafficServerConnector@797501a{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
    

    WireMock服务器可以在自己的进程中运行,并通过Java API、HTTP或JSON文件对其进行配置。

    下载地址
    http://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/2.19.0/wiremock-standalone-2.19.0.jar

    Once you have downloaded the standalone JAR you can run it simply by doing this:

    $ java -jar wiremock-standalone-2.19.0.jar
    

    命令行选项
    以下可以在命令行中指定:
    --port:设置HTTP端口号,例如端口9999。使用--port 0来动态确定端口.
    --https-port:如果指定,则在提供的端口上启用HTTPS.
    --bind-address:WireMock服务器应该提供的IP地址。如果未指定,则绑定到所有本地网络适配器。
    --https-keystore:包含用于HTTPS的SSL证书的密钥存储文件的路径。密钥存储库的密码必须为“password”。此选项仅在指定--https-port时才有效。如果没有使用此选项,WireMock将默认为它自己的自签名证书。

    六.与 SpringBoot 整合

    Spring Cloud Contract 已经创建了一个库来支持使用“ambient”HTTP服务器运行WireMock。它还简化了配置的某些方面,并消除了在同时运行Spring引导和WireMock时出现的一些常见问题。

    场景描述:项目有两个模块 A&B, 现在需要我负责模块 A,B 模块由另外一个人负责, 整个项目的运行需要 A 调用 B 的接口模块.但是运行单元测试的时候就需要 B 能够调通, 这个时候需要一个模块能够模拟 B 的接口.

    1.首先添加依赖,属于 SpringCloud,可以直接添加 SpringCloud 依赖,会自动整合合适的版本.

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-contract-wiremock</artifactId>
        <scope>test</scope>
    </dependency>
    
    

    2.编写Controller代码

    @RestController
    public class WireMockController {
    
        @Autowired
        private RemoteService service;
    
        @GetMapping("get")
        public String get() {
            return service.access();
        }
    
    }
    
    

    3.编写 Service 代码
    这个部分会通过 RestTemplate 调用远程摸个模块.

    @Service
    public class RemoteService {
    
        @Autowired
        private RestTemplate restTemplate;
    
        @Value("${remote}")
        private String url;
    
        public String access() {
            ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
            System.out.println(result);
            return result.getBody();
        }
    
    }
    

    4.编写单元测试

    @SpringBootTest
    @AutoConfigureMockMvc
    @ActiveProfiles("dev")
    @RunWith(SpringRunner.class)
    @AutoConfigureWireMock(stubs="classpath:/mappings")
    public class WireMockControllerTest {
    
        @Autowired
        private MockMvc mvc;
    
        @Rule
        public WireMockRule service1 = new WireMockRule(8090);
    
        @Test
        public void bothServicesDoStuff() throws Exception  {
            this.mvc.perform(MockMvcRequestBuilders.get("/get"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello World"));
        }
    }
    
    

    重点来了,
    运行 dev 配置文件:
    application-dev.properties

    remote=http://127.0.0.1:8080/hello
    

    把远程访问的地址改为本地
    在 resources 下面
    建立mappings文件夹,里面存入如下信息,文件以 .json 结尾:

    {
      "request" : {
        "urlPath" : "/hello",
        "method" : "GET"
      },
      "response" : {
        "status" : 200,
        "body" : "Hello World"
      }
    }
    

    @AutoConfigureWireMock(stubs="classpath:/mappings")表示在classpath:/mappings文件夹下添加一些映射,每个 json 文件都是一个映射. json文件可以指定访问方式,访问的路径,返回数据,状态码等等.

    六.代码路径

    https://github.com/shaopro/SpringBootWireMock

    相关文章

      网友评论

          本文标题:WireMock实战-1

          本文链接:https://www.haomeiwen.com/subject/wrarqqtx.html