我是靠谱客的博主 温婉百褶裙,这篇文章主要介绍Mockito stubbing,现在分享给大家,希望可以做个参考。

什么是Mock stubbing

打桩是一个形象的说法,就是把所需的测试数据塞进对象中,适用于基于状态的(state-based)测试,关注的是输入和输出。Mockito stubbing 打桩功能可以使被打桩的方法调用返回期望的值。Mockito通过Mockito.when().thenReturn()实现打桩功能,在when中定义对象方法和参数(输入),然后在 thenReturn 中指定结果(输出)。一旦这个方法被 stub 了,就会一直返回这个 stub 的值。

复制代码
1
2
3
4
    @CheckReturnValue     public static <T> OngoingStubbing<T> when(T methodCall) {         return MOCKITO_CORE.when(methodCall);     }
复制代码
1
OngoingStubbing<T> thenReturn(T value);

待测试类

service 依赖repository,service种的findAll()方法调用repository的findAll()方法获取Student的集合并且对获取到的Student集合 进行下一步处理时(比如更新所有学生的className),这时候在测试service时就可以用mockito的打桩功能,给repository的findAll()方法返回的是个固定值,然后在service中继续处理。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class StudentServiceImpl implements StudentService {     @Autowired     private StudentRepository studentRepository;     @Override     public List<StudentEntity> findAll() {         List<StudentEntity> studentEntities = studentRepository.findAll();         for (StudentEntity studentEntity : studentEntities) {             studentEntity.setClassName("new class name");         }         return studentEntities;     } }

准备测试数据数据

srctestresourcescomexamplesutdserviceimplstudentServicetestFindAllStudentEntityList.json

[
    {
        "seqId": "DK",
        "firstName": "jolin",
        "lastName": "li"
    },
    {
        "seqId": "DK1",
        "firstName": "tony",
        "lastName": "he"
    },
    {
        "seqId": "DK2",
        "firstName": "hani",
        "lastName": "zhang"
    }
]

测试类

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.io.IOException; import java.util.List; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; //被测试类 @SpringBootTest(classes = StudentServiceImpl.class) class StudentServiceImplTest {     @Autowired     private StudentServiceImpl studentService; // 注入被测试类     @MockBean     private StudentRepository studentRepository; // Mock被测试类的依赖     private String jsonPath = "/com/example/sutd/service/impl/studentService/";     @Test     void testFindAll() throws IOException {         // 准备测试数据并mock stubbing 打桩         List<StudentEntity> studentEntities = JsonObjectUtil.parseArrayFromJsonFile(jsonPath + "testFindAll/StudentEntityList.json", StudentEntity.class);         Mockito.when(studentRepository.findAll()).thenReturn(studentEntities);         //test         studentService.findAll();     } }

最后

以上就是温婉百褶裙最近收集整理的关于Mockito stubbing的全部内容,更多相关Mockito内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(80)

评论列表共有 0 条评论

立即
投稿
返回
顶部