Mockito mock 泛型类、泛型接口


#Java Mockito 测试框架


示例:

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

}


( 本文完 )