Search code examples
javaspringspring-bootjunitmockito

Mock is not working properly when i try to return optional


I'm writing a test for a method in which the repository should return a user, I've hardcoded this logic, but my mock returns an empty optional. Here is the method code

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

Here is the test code

@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);
}

Setting up mocks

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

@Autowired
private UserService userService;

@MockBean
private UserRepository userRepository;

@MockBean
private GroupRepository groupRepository;

@Captor
private ArgumentCaptor<AppChatMember> appChatMemberCaptor;

Here is getAppchatMember

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

Here is 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);

}


Solution

  • The problem was that there were 2 identical methods, but one took a primitive, and the second was an object type and Mockito mock te object type method, so solution is delete one from repository.