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

    带着疑问去思考,然后串联,进而归纳总结,不断追问自己,进行自我辩证,像侦查嫌疑案件一样看待技术问题,漆黑的街道,你我一起寻找线索,你就是技术界大侦探福尔摩斯
  • 相关阅读:
    Lesson 3 Nehe
    Lesson 2 Nehe
    Lesson 1 Nehe
    Lesson 1 Nehe
    JavaScript 字符串与数组转换函数[不用split与join]
    华中科大校长:教授被称为“叫兽”是教育的悲哀
    /etc/profile、~/.bash_profile等几个文件的执行过程
    cygwin下遇到system没有执行的问题
    发短信 汉字编码 utf-8 UCS-2BE
    UTF-8与UNICODE的关系及代码转换
  • 原文地址:https://www.cnblogs.com/cainiao-Shun666/p/14806628.html
Copyright © 2011-2022 走看看