• MockitoTest 单元测试


    package com.yiautos.psf.order.service.impl;
    
    import org.junit.Assert;
    import org.junit.Test;
    import org.mockito.Mockito;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class MockitoTest {
    
    
        @Test
        public void testBehavior() {
            //构建mock数据
            List<String> list = Mockito.mock(List.class);
            list.add("1");
            list.add("2");
    
            System.out.println(list.get(0)); // 会得到null ,前面只是在记录行为而已,没有往list中添加数据
    
            Mockito.verify(list).add("1"); // 正确,因为该行为被记住了
            Mockito.verify(list).add("3");//报错,因为前面没有记录这个行为
    
        }
    
        @Test
        public void testStub() {
            List<Integer> l = Mockito.mock(ArrayList.class);
    
            Mockito.when(l.get(0)).thenReturn(10);
            Mockito.when(l.get(1)).thenReturn(20);
            Mockito.when(l.get(2)).thenThrow(new RuntimeException("no such element"));
    
            Assert.assertEquals(10, (int) l.get(0));
            Assert.assertEquals(20, (int) l.get(1));
            Assert.assertNull(l.get(4));
            l.get(2);
        }
    
        @Test
        public void testSpy() {
            List<String> spyList = Mockito.spy(ArrayList.class);
    
            spyList.add("one");
            spyList.add("two");
    
            Mockito.verify(spyList).add("one");
            Mockito.verify(spyList).add("two");
    
            Assert.assertEquals(2, spyList.size());
    
            Mockito.doReturn(100).when(spyList).size();
            Assert.assertEquals(100, spyList.size());
        }
    
        @Test
        public void testVoidStub() {
            List<Integer> l = Mockito.mock(ArrayList.class);
            Mockito.doReturn(10).when(l).get(1);
            Mockito.doThrow(new RuntimeException("you cant clear this List")).when(l).clear();
    
            Assert.assertEquals(10, (int) l.get(1));
            l.clear();
        }
    
        @Test
        public void testMatchers() {
            List<Integer> l = Mockito.mock(ArrayList.class);
            Mockito.when(l.get(Mockito.anyInt())).thenReturn(100);
    
            Assert.assertEquals(100, (int)l.get(999));
        }
    }
  • 相关阅读:
    扑克牌顺子
    数组转 二叉树 ,并且输出二叉树的右视图
    数组中逆序对(归并排序思想)
    链表数字加和
    回文数字
    数组中 只出现一次的数
    判断是否有从根节点到叶子节点的节点值之和等于 sum
    双指针求 3个数和 为0的 数
    vue项目将css,js全部打包到html文件配置
    webpack4配置优化
  • 原文地址:https://www.cnblogs.com/deepalley/p/16158783.html
Copyright © 2020-2023  润新知