【发布时间】:2021-08-30 20:32:49
【问题描述】:
我要测试一个serviceImpl(UpdateServiceImpl),测试是这样的:
@SpringBootTest
public class UpdateUserServiceImplTests {
@Spy
UserRepository userRepository;
@Mock
private UserInfoUpdate userInfoUpdate;
@Autowired
UserRepository userRepository1;
@Spy
@InjectMocks
private UpdateUserServiceImpl updateUserServiceImpl;
@BeforeEach
public void setupMock() {
MockitoAnnotations.openMocks(this);
userInfoUpdate = new UserInfoUpdate();
}
@Test
public void makeUserInfoRight (){
try {
System.out.println(userInfoUpdate.getUsername());
User user = updateUserServiceImpl.makeUserInfoFull(userInfoUpdate);
User user_to_update = userRepository1.findById(userInfoUpdate.getUsername())
.orElseThrow(()
-> new UserNotFoundException("User not found by thisusername : " + "{" +
userInfoUpdate.getUsername() + "}"));
}
要测试的updateUserServiceImpl中的方法(makeUserInfoFull())是这样的:
@Service
public class UpdateUserServiceImpl implements UpdateUserService {
@Autowired
UserRepository userRepository;
@Autowired
InfoGuess infoGuess;
@Override
public User makeUserInfoFull(UserInfoUpdate userInfoUpdate)
throws UserNotFoundException {
User user_to_update =
userRepository.findById(userInfoUpdate.getUsername())
.orElseThrow(() -> new UserNotFoundException("User not found by this username : " + "{" + userInfoUpdate.getUsername() + "}"));
存储库很简单:
@Service
public interface UserRepository extends JpaRepository<User, String> {
}
JpaRepository 接口通过 @Autowired 在测试单元中正常工作(生成 userRepository1),但是方法中的接口( makeUserInfoFull() )我尝试使用@Spy 模拟到测试中,即存储库(例如:userRepository.findAll() ) 保持返回空结果。 是不是没有办法通过JpaRepositoy在测试中使用真实数据?
【问题讨论】:
标签: java jpa testing methods entity