Java单元测试Mockito如何用
作者:吹吹风会发光
时间:2023-04-26
浏览:2
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("张三"));
}
}
作者最新文章
Typora怎么插入表格?Ctrl+T快速建表并调整行列
2026-10-05 17:59
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
下一篇:
如何在iPhone上进行非侧面按钮截屏?
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多










































