• 单元测试-mock基础


    本文较短,只是备份一下mock的几个常用基础例子方便复习

    目录

    介绍mock的使用例子

    maven资源

            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-all</artifactId>
                <version>1.8.5</version>
            </dependency>

    1 mock一个对象

    annotation

    @Mock private TestOpt tt;

    静态方法调用

    List mockedList = Mockito.mock(ArrayList.class);

    2 mock传参与返回设定

     精确匹配

    public void case0() {//匹配调用
            List mockedList = Mockito.mock(ArrayList.class);
            Mockito.when(mockedList.get(0)).thenReturn("first");
            Mockito.when(mockedList.get(1)).thenThrow(new RuntimeException());
            System.out.println(mockedList.get(0));//first
            System.out.println(mockedList.get(1));//exception
        }

    模糊匹配

    public void case1(){//模糊调用
            TestOpt tt = Mockito.mock(TestOpt.class);
            Mockito.when(tt.one(Mockito.anyInt(), Mockito.anyInt())).thenReturn(3).thenReturn(4);//多次调用
            System.out.println(tt.one(3, 11));//3
            System.out.println(tt.one(3, 11));//4
        }

    3 调用次数判断并集合annotation使用

        @Mock private TestOpt tt;
        @Mock private service ser;
        @Test
        public void case2(){//调用次数+注解
            MockitoAnnotations.initMocks(this);//annotation调用
            Mockito.when(this.ser.services(1, 10)).thenReturn("100");
            Mockito.when(this.tt.one(1, 40)).thenReturn(20);
            System.out.println(ser.services(1, 10));System.out.println(ser.services(1, 9));

    //校验次数 tt.three(); tt.three(); System.
    out.println(tt.one(1, 40));System.out.println(tt.one(1, 33)); Mockito.verify(tt, Mockito.times(2)).three(); Mockito.verify(tt, Mockito.atLeast(1)).three(); Mockito.verify(tt, Mockito.atLeastOnce()).three(); // Mockito.verify(tt, Mockito.never()).three(); //从未调用 }

    随手写的类--用于测试

    public class TestOpt implements TestOptI {
        public int one(int a ,int b){
            return a+b;
        }
        public int two(int a ,int b){
            return one(a, b)+one(a, b)+one(a, b);
        }
        public int three(){
            return 300;
        }
    }
    public class service {
        TestOptI i = null;
        public String services(int a,int b){
            i = new TestOpt();
            return String.valueOf(i.one(a, 2)+i.three());
        }
    }
  • 相关阅读:
    基于ARP的网络扫描工具netdiscover
    渗透测试集成环境Faraday
    NBNS扫描工具nbtscan-unixwiz
    分享Kali Linux 2017年第18周镜像文件
    Hat's Fibonacci
    N!
    A + B Problem II(大数加法)
    产生冠军(拓扑排序)
    确定比赛名次
    Legal or Not(模板题)
  • 原文地址:https://www.cnblogs.com/sunfan1988/p/3638533.html
Copyright © 2020-2023  润新知