1

I have a spring boot project where I'm trying to mock my repository for tests. I would like my repository.count() to return 30L but it actually always return 0

@Service
@Transactional
public class DishServiceImpl implements DishService {

    private final DishRepository dishRepository;

    public DishServiceImpl(DishRepository dishRepository) {
        this.dishRepository = dishRepository;
    }

    @Override
    public List<Dish> searchDishes() {

        long countDish = dishRepository.count();

        System.out.println(countDish);
        [...]
    }
}

@RunWith(SpringRunner.class)
@SpringBootTest(classes = WhatAreWeEatingApp.class)
@Transactional
public class DishServiceTest{

    @Mock
    private DishRepository dishRepository;

    @Autowired
    private DishService dishService;

    @Test
    public void test(){

        when(dishRepository.count()).thenReturn(30L);
        dishService.searchDishes();

        [...]
    }
Antoine Grenard
  • 1,712
  • 3
  • 21
  • 41

1 Answers1

1

You repository mock is never set as dependency to the bean service.
Here you mock in the frame of a running Spring container :

@RunWith(SpringRunner.class)
@SpringBootTest(classes = WhatAreWeEatingApp.class)

It is not unit test. So you want to use @MockBean from Spring Boot to mock a bean in the container, not @Mock from Mockito to mock instances created outside the container.
Don't like auto promotional post but this question should help you.

To go further you should not need to run a container to test the service method. So you should probably remove the Spring Boot test annotation and write a real unit test.

davidxxx
  • 125,838
  • 23
  • 214
  • 215