Search code examples
javajunitmockito

Mockito returns Optional.empty instead of object for tests


Java 18, spring boot starter parent 3.0.4, junit 4.13.2

Debug shows me, that everywhere is the same mock for repository. "Evaluate expression" on taskRepository.findById(id) at service method shows that object is null instead of my created task object at init().

Code:

TaskRepository extends JpaRepository

My service method:

@Transactional
    public Task getTaskById(Integer id){
        Optional<Task> taskById = taskRepository.findById(id);
        if(taskById.isPresent()){
            return taskById.get();
        }

        throw new RuntimeException("Task not found with id : " + id);
    }

My test class:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@RunWith(MockitoJUnitRunner.class)
public class TaskServiceTestWithoutSpring {

    @Mock
    public TaskRepository taskRepository;

    @Spy
    @InjectMocks
    public TaskService taskService;

    @BeforeEach
    public void init(){
        MockitoAnnotations.openMocks(this);
        Task task = new Task();
        task.setId(4);
        task.setStatus(StatusEnum.IN_PROGRESS);
        task.setDescription("amazing task");

        doReturn(Optional.of(task)).when(taskRepository).findById(anyInt());
    }
}

I have tried change @Mock by @MockBean, call when(taskRepository.findById(anyInt())).thenReturn(Optional.of(task)); instead of current code, change anyInt() parameter to various mockito parameters

Any advices, please. Thanks in advance


Solution

  • try

    when(taskRepository.finById(anyInt()).thenReturn(Optional.of(task))
    

    on the test method with annotation @org.junit.jupiter.api.Test

    to improve your test method, thy this template

    @Test
    void testGetTaskById() {
            // given
            var anyId = 8
            var expected = new Task();
            expected.setId(4);
            expected.setStatus(StatusEnum.IN_PROGRESS);
            expected.setDescription("amazing task");
    
            // when
            when(taskRepository.finById(anyInt())).thenReturn(Optional.of(expected));
    
            // then
            Task actual = taskService.findById(8);
            org.assertj.core.api.Assertions.assertThat(actual)
                    .usingRecursiveComparison()
                    .isEqualTo(expected);
    }