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

    带着疑问去思考,然后串联,进而归纳总结,不断追问自己,进行自我辩证,像侦查嫌疑案件一样看待技术问题,漆黑的街道,你我一起寻找线索,你就是技术界大侦探福尔摩斯
  • 相关阅读:
    今天才知道还有这个地址 MS 的
    提供一个在线翻译,多语言互译的好网址.
    程序员有多少读过《人性的弱点》?项目经理呢?
    [下载]ASP.NET开发技巧集锦
    真不好意思,关于小猪妹(妖精)的
    poj 1330 LCA问题 (LCA问题转化为RMQ || tarjan算法)
    poj 2688 (bfs+dfs)
    Codeforces Round #143 (Div. 2) B
    poj 1160 dp
    poj 1032(整数拆分)
  • 原文地址:https://www.cnblogs.com/cainiao-Shun666/p/14806650.html
Copyright © 2011-2022 走看看