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

    带着疑问去思考,然后串联,进而归纳总结,不断追问自己,进行自我辩证,像侦查嫌疑案件一样看待技术问题,漆黑的街道,你我一起寻找线索,你就是技术界大侦探福尔摩斯
  • 相关阅读:
    dedecms织梦修改标题默认长度
    Python正课68 —— 实现面向对象编程
    Python正课67 —— 面向对象介绍
    Win10系统下提示VMware与Device/Credential Guard不兼容的解决方法
    周考5 月考1 内容
    Python正课66 —— ATM + 购物车 小有成就
    Python正课65 —— ATM + 购物车 架构
    Python正课64 —— re模块
    Python正课63 —— logging模块
    Python正课62 —— subprocess模块
  • 原文地址:https://www.cnblogs.com/cainiao-Shun666/p/14806650.html
Copyright © 2011-2022 走看看