1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、建立service相关类
实体类:
@Data
public class User {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
}
mapper类:
public interface UserRepository {
User findUserById(String id);
}
service类:
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findUserById(String id) {
return userRepository.findUserById(id);
}
}
3、使用mock
public class UserServiceTest {
private UserRepository userRepository;
private UserService userService;
@BeforeEach
void setUp() {
//创建模拟对象
userRepository = Mockito.mock(UserRepository.class);
userService = new UserService(userRepository);
}
@Test
void getUsernameById_exists() {
User user = new User("1", "周杰伦");
//配置模拟行为
Mockito.when(userRepository.findUserById("1")).thenReturn(user);
System.out.println(userService.findUserById("1"));
}
@Test
void getUsernameById_not_exists() {
Mockito.when(userRepository.findUserById("2")).thenReturn(null);
System.out.println(userService.findUserById("2"));
}
}