2.14 mock接口

作者: 孙兴斌 | 来源:发表于2016-12-27 17:40 被阅读41次

有些实现类是匿名的:

public interface Service { int doSomething(); }

public final class TestedUnit {

    private final Service service = new Service() { 
        public int doSomething() { return 2; } 
    };

    public int businessOperation() {
        return service.doSomething();
    }
}

使用@Capturing标注基类/接口,所有实现类会被mock:

@Capturing Service anyService;

@Test
public void mockingImplementationClassesFromAGivenBaseType() {
    new Expectations() {{ 
        anyService.doSomething(); 
        returns(3); 
    }};

    int result = new TestedUnit().businessOperation();
    assertEquals(3, result);
}

@Capturing@Mock的增强版,有一个可选参数maxInstances用于捕获前面指定数量的对象,其默认值为Integer.MAX_VALUE

@Test
public void TestMethod(@Capturing(maxInstances = 2) final Dependency dependency1,
                       @Capturing(maxInstances = 2) final Dependency dependency2,
                       @Capturing final Dependency remain) {
    new NonStrictExpectations() {{
        dependency1.getValue();
        result = 1;
        dependency2.getValue();
        result = 2;
        remain.getValue();
        result = 3;
    }};
    assertEquals(1, new Dependency().getValue());
    assertEquals(1, new Dependency().getValue());
    assertEquals(2, new Dependency().getValue());
    assertEquals(2, new Dependency().getValue());
    assertEquals(3, new Dependency().getValue());
}

上面的@Capturing是出现在参数列表中的,如果是作为field声明的,maxInstances会失效,@Capturing退化为@Mock

相关文章

  • 2.14 mock接口

    有些实现类是匿名的: 使用@Capturing标注基类/接口,所有实现类会被mock: @Capturing是@M...

  • 接口测试Mock与HttpClient

    1.Mock框架 1.1mock介绍: mock可以模拟接口测试,通过运行mock框架的jar,快速搭建接口测试。...

  • 接口文档工具 apiPost

    ApiPost = 接口调试+接口文档快速生成+接口文档规范化管理+Mock API+接口流程测试。 生成Mock...

  • mock配置

    后端配置 在apizz的接口中,切换到mock页,配置mock接口的路径(要与真实接口保持一致),同时填入mock...

  • 82.项目中使用mock

    1.引入mock 2.项目中新建mock目录,新建index.js3.定义接口和接口返回值,使用mock时用数据占...

  • "TypeError: Cannot read property

    原因: 前端请求mock的接口与mock不一致。

  • Python+ Flask轻松实现Mock Server

    1、什么是Mock 模拟接口 接口Mock测试:在接口测试中,对于某些不容易构造或者不容易获取的接口,可以用一个模...

  • 接口mock

    首页 产看用户 我关注谁 谁关注我 查看用户的所有收货地址 查看地区分区字典 用户正在的分享 用户查看草稿状态的分...

  • 开发相关工具-持续收集

    在线接口mock Easy Mock 抓包工具 CharlesAnyProxy[wireshark] 抓包工具Ch...

  • 前端 Mock

    Mock.js 生成随机数据,拦截 Ajax 请求 RAP Web接口管理工具,开源免费,接口自动化,MOCK数据...

网友评论

    本文标题:2.14 mock接口

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