Java单元测试Mockito如何用
作者:吹吹风会发光
时间:2023-04-26
来源:互联网
浏览:0
Mockito简介调用mock对象的方法时,不会执行真实的方法,而是返回类型的默认值,如object返回null,int返回0等,否则通过指定when(方法).thenReturn(value)来指定方法的返回值。同时mock对象可以进行跟踪,使用verify方法看是否已经被调用过。而spy对象,默认会执行真实方法,返回值可以通过when.thenReturn进行覆盖。可见mock只要避开了执行一些方法,直接返回指定的值,方便做其他测试。Service测试用例需要的依赖junitjunit4.12test
Mockito简介
调用mock对象的方法时,不会执行真实的方法,而是返回类型的默认值,如object返回null, int返回0等,否则通过指定when(方法).thenReturn(value)来指定方法的返回值。同时mock对象可以进行跟踪,使用verify方法看是否已经被调用过。而spy对象,默认会执行真实方法,返回值可以通过when.thenReturn进行覆盖。可见mock只要避开了执行一些方法,直接返回指定的值,方便做其他测试。
Service测试用例
需要的依赖
junit junit 4.12 test org.mockito mockito-core 2.23.4 test org.springframework.boot spring-boot-test 2.1.13.RELEASE
代码示例
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest()
public class StudentServiceTest {
@InjectMocks
StudentService studentService = new StudentServiceImpl();
@Mock
StudentDAO studentDAO;
@Before
public void before(){
Mockito.doReturn(new StudentDO("张三", 18)).when(studentDAO).read(Mockito.anyString());
}
@Test
public void testRead(){
StudentDO read = studentService.read("");
Assert.assertNotNull(read);
}
}Controller测试用例
需要的依赖
org.springframework spring-test 5.1.14.RELEASE com.jayway.jsonpath json-path 2.4.0
代码示例
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest()
public class StudentControllerTest {
@Resource
MockMvc mockMvc;
@InjectMocks
StudentController studentController;
@Mock
StudentService studentService;
@Before
public void before() {
mockMvc = MockMvcBuilders.standaloneSetup(studentController).build();
Mockito.doReturn(new StudentDO("张三", 18)).when(studentService).read(Mockito.anyString());
}
@Test
public void testRead() throws Exception {
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/student/read/1");
mockMvc.perform(request)
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("张三"));
}
}
作者最新文章
iphone蓝牙连接ipad有什么用及连接方法教程
2026-09-21 17:28
PDF怎么取消密码保护?4种解锁方法整理
2026-09-08 18:23
三星 Galaxy Z Fold8 内屏边角支撑偏软?实测与官方回应
2026-09-08 16:39
手机Excel表格制作教程:小屏幕高效录入与格式调整指南
2026-09-04 09:27
PDF文档按页转换成图片怎么做?在线转换步骤整理
2026-09-03 11:06
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















