spring 当我尝试返回可选值时,

fkvaft9z  于 2023-10-15  发布在  Spring
关注(0)|答案(1)|浏览(87)

我正在为一个方法编写一个测试,其中存储库应该返回一个用户,我已经硬编码了这个逻辑,但我的mock返回一个空的可选值。下面是方法代码

@Override
public AppChatMember getByTelegramId(long telegramId) {
    return userRepository.findByTelegramId(telegramId).orElseThrow(() -> new UserNotFoundException(
            String.format(USER_NOT_FOUND_BY_TG_ID, telegramId)));
}

下面是测试代码

@Test
@DisplayName("Checking that method is calling find by telegram id")
void getByTelegramIdShouldCallFindByTelegramId() {
    long expectedTelegramId = 123456L;
    AppChatMember user = getAppChatMember();

    when(userRepository.findByTelegramId(anyLong())).thenReturn(Optional.of(user));

    userService.getByTelegramId(expectedTelegramId);

    verify(userRepository, times(1)).findByTelegramId(expectedTelegramId);
}

设置模拟

@SpringBootTest
@ActiveProfiles("test")
class UserServiceImplTest {

@Autowired
private UserService userService;

@MockBean
private UserRepository userRepository;

@MockBean
private GroupRepository groupRepository;

@Captor
private ArgumentCaptor<AppChatMember> appChatMemberCaptor;

getAppchatMember

AppChatMember getAppChatMember() {
    AppChatMember user = new AppChatMember();
    user.setNickName("Nickname");
    user.setTelegramId(123456L);
    user.setIsProcessing(true);
    return user;
}

这里是userRepository

@Repository
public interface UserRepository extends     
JpaRepository<AppChatMember, Long> {

boolean existsByTelegramId(long telegramId);

Optional<AppChatMember> findByTelegramId(long telegramId);

Optional<AppChatMember> findByTelegramId(Long telegramId);

List<AppChatMember> findByCondition(UserConditionEnum condition);

}

sr4lhrrt

sr4lhrrt1#

问题是,有两个相同的方法,但一个采取了一个基本的,第二个是一个对象类型和Mockito模拟te对象类型方法,所以解决方案是从存储库中删除一个。

相关问题