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

    Mockito 测试隔离

    根据 JUnit 单测隔离 ,当 Mockito 和 JUnit 配合使用时,也会将非static变量或者非单例隔离开。

    比如使用 @Mock 修饰的 mock 对象在不同的单测中会被隔离开。

    示例:

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mock;
    import org.mockito.junit.MockitoJUnitRunner;
    
    import static org.mockito.Mockito.*;
    
    @RunWith(MockitoJUnitRunner.class)
    public class MockitoDemo {
    
        static class ExampleService {
    
            public int add(int a, int b) {
                return a+b;
            }
    
        }
    
        @Mock
        private ExampleService exampleService;
    
        @Test
        public void test01() {
            System.out.println("---call test01---");
    
            System.out.println("打桩前: " + exampleService.add(1, 2));
    
            when(exampleService.add(1, 2)).thenReturn(100);
    
            System.out.println("打桩后: " + exampleService.add(1, 2));
        }
    
        @Test
        public void test02() {
            System.out.println("---call test02---");
    
            System.out.println("打桩前: " + exampleService.add(1, 2));
    
            when(exampleService.add(1, 2)).thenReturn(100);
    
            System.out.println("打桩后: " + exampleService.add(1, 2));
        }
    
    }

    将两个单测一起运行,运行结果是:

    ---call test01---
    打桩前: 0
    打桩后: 100
    ---call test02---
    打桩前: 0
    打桩后: 100

    test01 先被执行,打桩前调用add(1, 2)的结果是0,打桩后是 100。

    然后 test02 被执行,打桩前调用add(1, 2)的结果是0,而非 100,这证明了我们上面的说法。

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

    带着疑问去思考,然后串联,进而归纳总结,不断追问自己,进行自我辩证,像侦查嫌疑案件一样看待技术问题,漆黑的街道,你我一起寻找线索,你就是技术界大侦探福尔摩斯
  • 相关阅读:
    如何让position:fixed在IE6中工作 不抖动
    【javascript基础】之【宿主环境】
    用函数式编程技术编写优美的 JavaScript
    IE6下使用滤镜后链接不能点击的BUG
    什么是内存泄漏
    Best Practices for Speeding Up Your Web Site
    Object.prototype.toString.call()
    【前端优化】IE浏览器下同一网页多图片显示的瓶颈与优化
    get username
    open file and format readin
  • 原文地址:https://www.cnblogs.com/cainiao-Shun666/p/14806650.html
Copyright © 2011-2022 走看看