Mockito简介以及代码例子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linjpg/article/details/89262287

Mockito也是一个开源的mock工具包,和EasyMock不同的时,它不需要录制、播放这些动作,语法上更灵活,可读性更强

官网:mockito
官方文档:mockito.html

范例代码

1.maven工程的话,首先引入pom包:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.7.12</version>
    <scope>test</scope>
</dependency>

2.测试类中引入静态资源:

import static org.mockito.Mockito.*; 

3.支持以下特性:(源码来自官方文档)

  • 验证行为有没有被调用过
//create mock
List mockedList = mock(List.class);
//use mock object
mockedList.add("one");
mockedList.clear();
//验证add方法是否在前面被调用了一次,且参数为“one”。clear方法同样。
verify(mockedList).add("one");
verify(mockedList).clear();
//下面的验证会失败。因为没有调用过add("two")。
verify(mockedList).add("two");
  • 插桩:使mock对象的方法返回期望值
    对于没有stub过的有返回值的方法,会返回默认值(0,false,null等)
//stubbing。当get(0)被调用时,返回"first". 方法get(1)被调用时,抛异常。
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());

重复stub

//重复stub,以最后一次为准,如下将返回"second":
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(0)).thenReturn("second");
//如下表示第一次调用时返回“first”,第二次调用时返回“second”。可以写n个。
when(mockedList.get(0)).thenReturn("first").thenReturn("second");
如果实际调用的次数超过了stub过的次数,则返回最后一次stub的值。
例如第三次调用get(0)时,则会返回"second".
  • 参数匹配
    如果想实现get(任意整数)时,都返回null,如何做?
when(mockedlist.get(anyInt())).thenReturn(null);

有许多的arguments matcher,参考More ArgumentMatchers
Argument matcher支持定制

  • 验证方法被调用了特定次数/至少x次/最多x次/从未被调用/返回结果是否是自己想要的结果
//是否add("twice")被调用了两次。
verify(mockedList, times(2)).add("twice");
//验证add("twice")被调用了至少一次。以及其他。
verify(mockedList, atLeastOnce()).add("twice");
verify(mockedList, atLeast(2)).add("twice");
verify(mockedList, atMost(5)).add("twice");
verify(mockedList, never()).add("twice");
  • 调用方法时抛出异常
doThrow(new RuntimeException()).when(mockedList).clear();
  • 验证顺序
    一个mock对象的方法以特定顺序被调用多次
    多个mock对象以特定顺序被调用多次
inOrder.verify(firstMock).add("was called first");
inOrder.verify(secondMock).add("was called second");

其中,插桩(stubbing)mock对象的返回值是测试中最常用到的

verify更适合那些没有返回值的方法 测试方法中某个调用是否真正的被调用过。

比如

   
    @Override
    public void save(Survey survey) {
        mongoTemplate.save(survey);
    }

测试方法可以这样写

@InjectMocks
    private QuestionServiceImpl questionService;
    @Mock
    private MongoTemplate mongoTemplate;
    @Mock
    private Survey survey;
    @Test
    public void save() throws Exception {
        questionService.save(survey);
        verify(mongoTemplate).save(survey);
    }

对于有返回值的方法,可以用assertThat这个例如:

@Override
    public long getTotalCountByUserName(String userName) throws Exception {
        Query query = new Query();
        query.addCriteria(Criteria.where("userName").is(userName));
        return mongoTemplate.count(query, Score.class, DocConstant.SCORE);
    }

测试方法这样写

@Test
    public void getTotalCountByUserName() throws Exception{
        when(scoreService.getTotalCountByUserName("xiaoming")).thenReturn(2l);
        long count = scoreService.getTotalCountByUserName("xiaoming");
        assertThat(count, is(2l));
    }
when(scoreService.getTotalCountByUserName("xiaoming")).thenReturn(2l);
这句代码就是当调用这个方法的时候返回21,
long count = scoreService.getTotalCountByUserName("xiaoming");
assertThat(count, is(2l));
这句代码就是说调用这个方法后,判断返回值是否是21 ,如果是就测试通过,否则就测试失败。

猜你喜欢

转载自blog.csdn.net/linjpg/article/details/89262287
今日推荐