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接口

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