gpt4 book ai didi

java - 测试包含模拟 JPA 存储库的服务时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 17:41:20 26 4
gpt4 key购买 nike

我正在开发我的第一个 Spring Boot 项目,作为 Mockito 新手,我在测试我的类时遇到了麻烦。我需要检查下面的 findAndUpdateUser 方法是否正确更新用户实体字段:

@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepo;

public User findUser(String id) {
return userRepo.findById(id);
}

public User findAndUpdateUser(String id) {
User foundUser = findUser(id);
//some update on foundUser fields
return foundUser;
}
}

为了测试,我需要模拟实体 bean,因为我本地没有数据库。这是我的测试类(class):

@RunWith(MockitoJUnitRunner.class)
public class UpdateFieldsTest {
@Mock
private UserRepository userRepo;

@Test
public void test1() {
User user = new User();
user.setId("testId");
//setting some other user fields

Mockito.when(userRepo.findById("testId")).thenReturn(user);
UserServiceImpl userService = new userServiceImpl();
User returnedUser = userService.findAndUpdateUser("testId");

//Checking if user field values are updated after findAndUpdate call
Assert.xxx
//other asserts
}
}

但是这段代码在方法调用时抛出了一些 NullPointerException 异常。我什至尝试模拟 findUser 方法,但仍然有错误...

我的方法不好吗?我应该如何测试我的方法?

欢迎任何帮助谢谢大家

最佳答案

使用这个实例化 UserServiceImpl userService = new userServiceImpl();使 UserRepo 为空;

你正在使用mockito,所以你可以使用
@InjectMocks
private UserServiceImpl;
并删除实例化行。

关于java - 测试包含模拟 JPA 存储库的服务时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60737026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com