简体   繁体   中英

Spy object keeps calling to real method even when stubbed

I am working on unit testing this service method, which requires using other methods in the same class that is being tested. So I have read about spy and applied it to my code. However, even when stubbed, the spy object of the class that I am testing keeps executing the real methods.

The method that is being tested

@Override
    public CategoryResponseDto updateCategory(Long categoryId, UpdateCategoryRequestDto requestDto) {
        CategoryEntity categoryEntity = findById(categoryId);

        modelMapper.convertToEntity(requestDto, categoryEntity);
        categoryEntity = categoryRepository.save(categoryEntity);

        return modelMapper.convertToResponse(categoryEntity, CategoryResponseDto.class);
    }

My code to test it

    @Test
    public void updateCategory_ShouldReturnCategoryResponseDto_WhenDataValid() {
        CategoryEntity categoryEntity = mock(CategoryEntity.class);
        UpdateCategoryRequestDto requestDto = mock(UpdateCategoryRequestDto.class);
        CategoryCrudServiceImpl spy = Mockito.spy(categoryCrudService);
        CategoryResponseDto expectedResult = mock(CategoryResponseDto.class);

        doReturn(categoryEntity).when(spy).findById(anyLong());
        when(categoryRepository.save(categoryEntity)).thenReturn(categoryEntity);
        when(modelMapper.convertToResponse(categoryEntity, CategoryResponseDto.class)).thenReturn(expectedResult);

        CategoryResponseDto result = categoryCrudService.updateCategory(1L, requestDto);

        assertThat(result, is(expectedResult));
    }

So the class being tested here is CategoryCrudServiceImple , the instance of that class is categoryCrudService in my test code and I create a spy out of it spy(categoryCrudService) . As you can see, I stubbed the findById() which comes from the same CategoryCrudServiceImple class with doReturn(categoryEntity).when(spy).findById(1L); and It didn't work, I tried passing in any() or anyLong() and the real findById() method is still called and throws the exception of ResourceNotFound .

Could you please help me with this? Am I missing or misunderstanding anything here?

Thank you very much for your precious time.

Well, thanks to the above comment of @Tom, I managed to get it right because I did not use spy here CategoryResponseDto result = categoryCrudService.updateCategory(1L, requestDto); . It should be like this CategoryResponseDto result = spy .updateCategory(1L, requestDto); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM