Mockito 参数匹配顺序


如果参数匹配即生命了精确匹配,也声明了模糊匹配;又或者同一个值的精确匹配出现了两次,使用时会匹配哪一个?

会匹配符合匹配条件的最新声明的匹配。

示例:

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.List;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class MockitoDemo {


    @Mock
    private List<String> testList;

    @Test
    public void test01() {

        // 精确匹配 0
        when(testList.get(0)).thenReturn("a");

        Assert.assertEquals("a", testList.get(0));

        // 精确匹配 0
        when(testList.get(0)).thenReturn("b");

        Assert.assertEquals("b", testList.get(0));

        // 模糊匹配
        when(testList.get(anyInt())).thenReturn("c");

        Assert.assertEquals("c", testList.get(0));
        Assert.assertEquals("c", testList.get(1));

    }

    @Test
    public void test02() {

        // 模糊匹配
        when(testList.get(anyInt())).thenReturn("c");

        Assert.assertEquals("c", testList.get(0));
        Assert.assertEquals("c", testList.get(1));

        // 精确匹配 0
        when(testList.get(0)).thenReturn("a");

        Assert.assertEquals("a", testList.get(0));
        Assert.assertEquals("c", testList.get(1));

    }

}



(本文完)


Mockito 教程