zoukankan      html  css  js  c++  java
  • Mockito (十九)

    Mockito 使用 verify 校验是否发生过某些操作

    使用 verify 可以校验 mock 对象是否发生过某些操作

    示例

    import org.junit.Test;
    
    import static org.mockito.Mockito.*;
    
    public class MockitoDemo {
    
        static class ExampleService {
    
            public int add(int a, int b) {
                return a+b;
            }
    
        }
    
        @Test
        public void test() {
    
            ExampleService exampleService = mock(ExampleService.class);
    
            // 设置让 add(1,2) 返回 100
            when(exampleService.add(1, 2)).thenReturn(100);
    
            exampleService.add(1, 2);
    
            // 校验是否调用过 add(1, 2) -> 校验通过
            verify(exampleService).add(1, 2);
    
            // 校验是否调用过 add(2, 2) -> 校验不通过
            verify(exampleService).add(2, 2);
    
        }
    
    }

    verify 配合 time 方法,可以校验某些操作发生的次数

    示例:

    import org.junit.Test;
    
    import static org.mockito.Mockito.*;
    
    public class MockitoDemo {
    
        static class ExampleService {
    
            public int add(int a, int b) {
                return a+b;
            }
    
        }
    
        @Test
        public void test() {
    
            ExampleService exampleService = mock(ExampleService.class);
    
            // 第1次调用
            exampleService.add(1, 2);
    
            // 校验是否调用过一次 add(1, 2) -> 校验通过
            verify(exampleService, times(1)).add(1, 2);
    
            // 第2次调用
            exampleService.add(1, 2);
    
            // 校验是否调用过两次 add(1, 2) -> 校验通过
            verify(exampleService, times(2)).add(1, 2);
    
        }
    
    }

    转载:https://www.letianbiji.com/java-mockito/mockito-verify.html

    带着疑问去思考,然后串联,进而归纳总结,不断追问自己,进行自我辩证,像侦查嫌疑案件一样看待技术问题,漆黑的街道,你我一起寻找线索,你就是技术界大侦探福尔摩斯
  • 相关阅读:
    iOS-25个小技巧
    iOS-UITableView的使用
    iOS-UIPickerView
    iOS-UIStoryboard和UIResponder
    javascript弹出层-DEMO001
    jQuery源码分析-02正则表达式-RegExp-常用正则表达式
    JSON动态生成树
    回顾码农历程总结2013 期待2014
    大数据量分页存储过程效率测试附代码
    关于对象序列化json 说说
  • 原文地址:https://www.cnblogs.com/cainiao-Shun666/p/14806628.html
Copyright © 2011-2022 走看看