JMockit教程(官方文档翻译版)Java学习笔记

2.14 mock接口

2016-12-27  本文已影响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

上一篇 下一篇

猜你喜欢

热点阅读