Mockito是什么?
MOCK意思是模拟的意思,主要被用来进行数据的人工组织,不会真正地调用第三方服务器,类似redis,mysql等都不会调用,也不用关心数据底层是如何进行处理的,我们要做的只是将本单元的逻辑进行单元测试,验证数据的逻辑处理性,而其中mock较好的框架就是Mockito。
Mockito是mocking框架,它让你用简洁的API做测试。而且Mockito简单易学,它可读性强和验证语法简洁。
1.首先创建springboot项目,并在pom文件引入Mockito依赖:
<dependency>
<groupId>org.mockitogroupId>
<artifactId>mockito-coreartifactId>
<version>3.3.3version>
dependency>
2.创建实体类(Student):
package com.example.mockito_test.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* @author Keson
* @version 1.0
* @description: TODO
* @date 2021/7/21 11:05
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Student {
private String id;
private String name;
private Integer age;
private String sex;
private String phoneNumber;
}
3.创建dao层:
package com.example.mockito_test.dao;
import com.example.mockito_test.entity.Student;
import org.springframework.stereotype.Repository;
/**
* @author Keson
* @version 1.0
* @description: TODO
* @date 2021/7/21 11:14
*/
@Repository
public class StudentDao {
//演示从数据库查询数据
public Student getById(String id){
Student student = new Student();
if(id.equals("001")){
student.setId("001");
student.setName("张三");
student.setAge(20);
student.setSex("男");
student.setPhoneNumber("12345678910");
}
return student;
}
//演示从数据库添加数据
public String save(Student student){
if(student != null){
return "数据成功添加";
}
return "数据添加失败";
}
}
4.创建service层:
package com.example.mockito_test.service;
import com.example.mockito_test.entity.Student;
/**
* @author Keson
* @version 1.0
* @description: TODO
* @date 2021/7/21 11:20
*/
public interface StudentService {
public Student getById(String id);
public String save(Student student);
}
package com.example.mockito_test.service.Impl;
import com.example.mockito_test.dao.StudentDao;
import com.example.mockito_test.entity.Student;
import com.example.mockito_test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author Keson
* @version 1.0
* @description: TODO
* @date 2021/7/21 11:21
*/
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public Student getById(String id) {
return studentDao.getById(id);
}
@Override
public String save(Student student) {
return studentDao.save(student);
}
}
5.创建controller层:
package com.example.mockito_test.controller;
import com.example.mockito_test.entity.Student;
import com.example.mockito_test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author Keson
* @version 1.0
* @description: TODO
* @date 2021/7/21 11:23
*/
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/getById")
public Student getById(@RequestParam("id") String id){
return studentService.getById(id);
}
@PostMapping("/save")
public String save(@RequestBody Student student){
return studentService.save(student);
}
}
1.快捷创建测试类方式:鼠标悬浮在类名上,按快捷键Alt+Enter
,点击Create Test:
2.创建完成后点开test包,里面出现刚刚创建好的测试类:
3.service测试类代码如下:
package com.example.mockito_test.service;
import com.example.mockito_test.dao.StudentDao;
import com.example.mockito_test.entity.Student;
import com.example.mockito_test.service.Impl.StudentServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
class StudentServiceTest {
@InjectMocks
StudentServiceImpl studentService;
@Mock
StudentDao studentDao;
@BeforeEach
void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
}
@Test
public void getById(){
Student student = new Student();
student.setId("001");
student.setName("张三");
//when里面带的是条件,thenReturn里面表示的是返回结果
Mockito.when(studentDao.getById("001"))
.thenReturn(student);
//assertThat后面跟着断言的判断语句
assertThat(studentService.getById(student.getId()).getName())
.isEqualTo("张三");
}
@Test
public void save(){
Student student = new Student();
student.setId("002");
student.setName("李四");
//when里面带的是条件,thenReturn里面表示的是返回结果
Mockito.when(studentDao.save(student))
.thenReturn("数据成功添加");
//assertThat后面跟着断言的判断语句
assertThat(studentService.save(student))
.isEqualTo("数据成功添加");
}
}
其中, Mockito.when()里面带的是条件,thenReturn里面表示的是返回结果。
如果结果判断正确的话,测试通过:
反之我们将“张三”改成“张三123”,测试失败,控制台输出提示:
代码如下所示:
package com.example.mockito_test.controller;
import com.example.mockito_test.entity.Student;
import com.example.mockito_test.service.StudentService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@AutoConfigureMockMvc
@ContextConfiguration(classes = {StudentController.class, StudentService.class})
@WebMvcTest
class StudentControllerTest {
@Autowired
private MockMvc mockMvc;
@InjectMocks
StudentController studentController;
@MockBean
StudentService studentService;
@Autowired
ObjectMapper objectMapper;
@BeforeEach
public void setUp(){
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(studentController).build();
}
@Test
public void getById() throws Exception {
Student student = new Student();
student.setId("001");
student.setName("张三");
Mockito.when(studentService.getById("001"))
.thenReturn(student);
mockMvc.perform(MockMvcRequestBuilders.get("/student/getById?id=001"))
//需要携带的头信息,如token信息 header("Authorization","Bearer ..."))
// .header("",""))
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void save() throws Exception {
Student student = new Student();
student.setId("002");
student.setName("李四");
Mockito.when(studentService.save(student))
.thenReturn("数据成功添加");
mockMvc.perform(MockMvcRequestBuilders.get("/student/save")
.contentType("application/json")
//需要携带的头信息,如token信息 header("Authorization","Bearer ..."))
// .header("",""))
//将请求实体转换成String放入content里面
.content(objectMapper.writeValueAsString(student)))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
注意,get请求与post请求测试方式不一致,注意区分!