'user repository is not Mocking in spring boot junit

I want to test one of my UserService methods with JUnit in SpringBoot

here is my UserService class:

import io.project.exception.NotFoundException;
import io.project.logger.CrudOperationLogger;
import io.project.model.user.UserDTO;
import io.project.model.user.UserEntity;
import io.project.model.user.UserMapper;
import io.project.repository.UserRepository;
import io.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private final CrudOperationLogger logger;
    private final UserRepository repository;
    private final UserMapper userMapper;

    public UserServiceImpl(CrudOperationLogger logger, UserRepository repository, UserMapper userMapper) {
        this.logger = logger;
        this.repository = repository;
        this.userMapper = userMapper;
    }

    @Override
    public UserDTO createUser(UserDTO userDTO) {
        UserEntity userEntity = userMapper.dtoToEntity(userDTO);
        userEntity = repository.save(userEntity);
        logger.createInfo(userEntity);
        return userMapper.entityToDto(userEntity);
    }

    @Override
    public List<UserDTO> getAllUsers() {
        List<UserDTO> userDTOS = new ArrayList<>();
        List<UserEntity> userEntities = repository.findAll();
        for (UserEntity userEntity : userEntities)
            userDTOS.add(userMapper.entityToDto(userEntity));

        logger.readInfo(userEntities);
        return userDTOS;
    }

    @Override
    public UserDTO getUserById(Long id) {
        Optional<UserEntity> optionalUserEntity = repository.findById(id);
        if (optionalUserEntity.isEmpty())
            throw new NotFoundException("user", id);
        return userMapper.entityToDto(optionalUserEntity.get());
    }
}

and here is my UserReposity:

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

and here is my UserServiceImplTest:

import io.project.model.user.UserDTO;
import io.project.model.user.UserEntity;
import io.project.model.user.UserMapperImpl;
import io.project.repository.UserRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.when;

@SpringBootTest(classes = {UserMapperImpl.class})
class UserServiceImplTest {
    private UserEntity fakeUserEntity;
    @Mock
    private UserRepository repository;

    @InjectMocks
    private UserServiceImpl userService;

    @BeforeEach
    void onCreate() {
        MockitoAnnotations.openMocks(this);

        fakeUserEntity = new UserEntity();
        fakeUserEntity.setId(1L);
        fakeUserEntity.setName("Mohammad");
    }

    @Test
    void getUserById() {
        when(repository.findById(anyLong())).thenReturn(Optional.of(fakeUserEntity));

        UserDTO userDTO = userService.getUserById(fakeUserEntity.getId());

        assertEquals(fakeUserEntity.getName(), userDTO.getName());
    }

and here is my build.gradle

plugins {
    id 'org.springframework.boot' version '2.6.7'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'io.project'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = "17"

configurations {
    all*.exclude module : 'spring-boot-starter-logging'
    all*.exclude module : 'logback-classic'
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springdoc:springdoc-openapi-ui:1.6.8'
    implementation 'org.mapstruct:mapstruct:1.4.2.Final'
    implementation 'org.springframework.boot:spring-boot-starter-validation'

    implementation 'org.slf4j:slf4j-api:1.7.36'
    implementation 'org.slf4j:slf4j-log4j12:1.7.36'

    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
    runtimeOnly 'com.h2database:h2'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.mockito:mockito-core:4.5.1'
    testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.8.2'

}

tasks.named('test') {
    useJUnitPlatform()
}
targetCompatibility = JavaVersion.VERSION_17


    

when I run this code I expect to pass the test but I get this error

io.project.exception.NotFoundException: user with id 1 not found

this error is the one i wrote in my UserServiceImpl.getUserById

any idea why this is happening?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source