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();
        }
    }
}

 

posted @ 2020-11-23 16:17  氯雷他定  阅读(231)  评论(0编辑  收藏  举报