用java举例,mockito传对象都是null
时间: 2024-05-15 15:14:55 浏览: 18
假设有以下代码:
```java
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public boolean createUser(User user) {
if (user == null) {
return false;
}
return userRepository.save(user);
}
}
```
我们想要使用 Mockito 对 `UserRepository` 进行单元测试,但是传入的 `User` 对象为 `null`,可以使用以下代码进行测试:
```java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.*;
class UserServiceTest {
@Test
void testCreateUserWithNullObject() {
UserRepository userRepository = mock(UserRepository.class);
UserService userService = new UserService(userRepository);
boolean result = userService.createUser(null);
assertFalse(result);
verify(userRepository, never()).save(any());
}
}
```
在这个测试中,我们使用 `mock` 方法创建了一个 `UserRepository` 的 Mock 对象,并传递给 `UserService` 的构造函数。然后我们调用 `createUser` 方法,并传入 `null` 对象。最后我们验证 `UserRepository.save` 方法从未被调用过。
这个测试用例通过了,说明我们的 `UserService` 对 `null` 对象做了正确的处理,避免了空指针异常。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)