一、新建工程
Student
package com.cattle.mockito.domain; /** * @author by XXX * @descriptaion # * @date 2020/6/11 */ public class Student { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Student(int id, int age, String name) { this.id = id; this.age = age; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } private int age; private String name; }
StudentDao
package com.cattle.mockito.dao; import com.cattle.mockito.domain.Student; import org.springframework.stereotype.Component; /** * @author by XXX * @descriptaion # * @date 2020/6/11 */ @Component public class StudentDao { public Student getStudentById(int id) { return new Student(1, 10, "Tony"); } }
StudentService
package com.cattle.mockito.service; import com.cattle.mockito.dao.StudentDao; import com.cattle.mockito.domain.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author by XXX * @descriptaion # * @date 2020/6/11 */ @Service public class StudentService { @Autowired StudentDao studentDao; public Student getStudentById(int id) { return studentDao.getStudentById(id); } }
Pom
自动生成的pom有缺失需添加以下依赖
4.0.0org.springframework.bootspring-boot-starter-parent2.3.0.RELEASEcom.cattlemockito0.0.1-SNAPSHOTmockitoDemo project for Spring Boot1.8org.springframework.bootspring-boot-starter-weborg.junit.platformjunit-platform-launchertestorg.springframework.bootspring-boot-starter-testtestorg.junit.vintagejunit-vintage-engineorg.apache.maven.pluginsmaven-compiler-plugin1.81.8UTF-8org.springframework.bootspring-boot-maven-plugin
生成测试类
package com.cattle.mockito.service; import com.cattle.mockito.dao.StudentDao; import com.cattle.mockito.domain.Student; import org.junit.jupiter.api.BeforeEach; 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.util.Assert; /** * @author by XXX * @descriptaion # * @date 2020/6/11 */ @SpringBootTest class StudentServiceTest { @Autowired StudentService studentService; @Autowired StudentDao studentDao; @BeforeEach void setUp() { // 执行测试之前进行更改 Mockito.when(studentDao.getStudentById(1)).thenReturn(new Student(1, 18, "cattle")); } @Test void getStudentById() { Student student = studentService.getStudentById(1); System.out.println(student.getAge()); System.out.println(student.getName()); System.out.println(student.getId()); } }
源码:https://gitee.com/jakhyd/JunitTest