springboot的Mockito的使用示例
时间: 2024-05-14 11:15:49 浏览: 12
好的,关于springboot的Mockito使用示例,以下是一段基本代码示例:
```
@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
public void testCreateUser() {
// given
User user = new User("123456", "Alice", "alice@example.com");
// when
when(userRepository.save(any(User.class))).thenReturn(user);
User createdUser = userService.createUser(user);
// then
assertNotNull(createdUser);
assertEquals("123456", createdUser.getId());
assertEquals("Alice", createdUser.getName());
assertEquals("alice@example.com", createdUser.getEmail());
}
}
```
以上是一个基本的UserServiceTest测试类,其中包含了假数据的初始化,Mockito框架对UserRepository的模拟对象,以及注入模拟对象。在testCreateUser()方法中,我们使用了when方法模拟了userRepository的save方法,使其返回我们设定的假数据。最后我们再对userService的createUser方法进行校验,判断是否传入的数据与模拟的数据一致。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)