zoukankan      html  css  js  c++  java
  • 7. 参数匹配:eq、isA、any

    package lesson7;
    
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.mockito.runners.MockitoJUnitRunner;
    import java.util.ArrayList;
    import java.util.List;
    import static org.mockito.Matchers.eq;
    import static org.mockito.Mockito.*;
    
    @RunWith(MockitoJUnitRunner.class)
    public class ArgumentsMatcherTest {
    
        @Test
        public void basicTest() {
            List<String> list = mock(ArrayList.class);
    //        when(list.get(0)).thenReturn("0");
            /** eq */
            when(list.get(eq(0))).thenReturn("0");
            Assert.assertEquals("0", list.get(0));
            Assert.assertEquals(null, list.get(1));
    
        }
    
        @Test
        public void complexTest() {
            Foo foo = mock(Foo.class);
            /** isA */
            when(foo.func(Mockito.isA(Child1.class))).thenReturn(100);
            int result = foo.func(new Child1());
            Assert.assertEquals(100, result);
            int result2 = foo.func(new Child2());
            Assert.assertEquals(0, result2);
    
            /** 清除foo的mock对象的所有stubbing*/
            reset(foo);
    
            /** any */
            when(foo.func(Mockito.any(Child1.class))).thenReturn(100);
            int result11 = foo.func(new Child2());
            Assert.assertEquals(100, result11);
        }
    
        static class Foo {
            int func(Parent p) {
                return p.work();
            }
        }
    
        interface Parent {
            int work();
        }
    
        class Child1 implements Parent {
            @Override
            public int work() {
                throw new RuntimeException();
            }
        }
    
        class Child2 implements Parent {
            @Override
            public int work() {
                throw new RuntimeException();
            }
        }
    }
  • 相关阅读:
    Hadoop入门
    Redis缓存分布式高可用架构原理
    ES分布式搜索引擎架构原理
    Java锁,多线程与高并发,JUC并发包
    图算法--拓扑序列
    数据结构--数组模拟队列
    数据结构--数组模拟栈
    数据结构--数组模拟双链表
    数据结构--数组模拟单链表
    基础算法--双指针
  • 原文地址:https://www.cnblogs.com/yfzhou528/p/14025122.html
Copyright © 2011-2022 走看看