Mockito (五)

Mockito mock 泛型类、泛型接口

示例:

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;

import static org.mockito.Mockito.*;

public class MockitoDemo {

    @Test
    public void test() {
        ArrayList<String> mockList = mock(ArrayList.class);  // 这种写法不够精确,IDE也会警告

        when(mockList.get(0)).thenReturn("abc");

        Assert.assertEquals(3, mockList.get(0).length());
    }

}

下面这种用 @Mock 注解的方法,IDE 不会警告:

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.ArrayList;

import static org.mockito.Mockito.*;

public class MockitoDemo {

    @Mock
    private ArrayList<String> mockList;

    @Test
    public void test() {

        MockitoAnnotations.initMocks(this);

        when(mockList.get(0)).thenReturn("abc");

        Assert.assertEquals(3, mockList.get(0).length());
    }

}

转载:https://www.letianbiji.com/java-mockito/mockito-mock-generic.html

 

posted @ 2021-05-24 14:59  迷走神经  阅读(385)  评论(0编辑  收藏  举报