Mockito 学习笔记

下载安装mockito安装包

https://start.spring.io/ 将自动生成的工程解压导入IDE中,项目中自动会带有mockito的jar包,可直接使用。


public class MockitoTest{

    @Test
    public void testFindTheGreatestFromAllData(){
        
        DataService dataServiceMock = mock(DataService.class);
        when(dataServiceMock.retrieAllData()).thenReturn(new int[]{30,19,100});
        SomeBUsinessImpl businessImpl = new SomeBusinessImpl(dataServiceMock);
        int resutl = businessImpl.findTheGreatestFromAllData();
        assertEquals(24.result);


    }

}

以下为注解的方式使用mockito

@RunWith(MockitoJUnitRunner.class)
public class MockitoAnnotationTest{
    @Mock
    DataService dataServiceMock;
    
    @InjectMocks
    SomeBusinessImpl businessImpl;//注解将dataServiceMock 注入impl中

    
    @Test
    public void testFindTheGreatestFromAllData(){

        when(dataServiceMock.retrieveAllData()).thenReturn(new int[]{34,100,8});
        int result = businessImpl.findTheGreatestFromAllData();
        assertEquals(100,result);

    }

}

 

mock List

public class ListTest{

    @Test
    public void test(){

        List listMock = mock(List.class);
        when(listMock.size()).thenReturn(10);
        assertEquals(10,listMock.size());

    }

    @Test
    public void test_mutipleReturns(){
        List listMock = mock(List.class);
        when(listMock.size()).thenReturn(10).thenReturn(20);
        assertEquals(10,listMock.size()); //firt time called return 10
        assertEquals(20,listMock.size()); //second time called return 20
        assertEquals(20,listMock.size()); //third time called return the last value 20
    }

    @Test
    public void testGet_specifiedParameter(){
        List listMock = mock(List.class);
        when(listMock.get(0)).thenReturn("something");
        assertEquals("something",listMock.get(0));
        assertEquals(null,listMock.get(1));

    }

    @Test
    public void testGet_genericParameter(){
        List listMock = mock(List.class);
        //如何一个方法可以传入多个参数,那么只要有一个参数传入generic,其他参数都必须为generic
        when(listMock.get(Mockito.anyInt())).thenReturn("something");
        assertEquals("someString",listMock.get(0));
        assertEquals("something",listMock.get(1));
        
    }



}

 

发布了4 篇原创文章 · 获赞 2 · 访问量 475
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览