javaspringspring-bootmockingmockito

How to mock repository Spring


My test class looks this way and I try to mock repository to return list of real objects.

In debug, I see that hashes of mock repository and service's repository during test are the same. Nonetheless I anyway receive empty ArrayList.

None of the previous answers like this or this etc. helped me.

@RunWith(SpringRunner.class)
@SpringBootTest
class MyServiceTest {

    @Mock
    private BasicStuffRepository<Stuff> stuffRepository;

    @Autowired
    private MyService myService;

    @Test
    void run() {
        // mock
        var mockObject1 = new Stuff();
        var mockObject2 = new Stuff();
        var mockObject3 = new Stuff();
        var mockObject4 = new Stuff();

        List<Stuff> mockStuff = Stream.of(mockObject1, mockObject2, mockObject3, mockObject4).collect(Collectors.toList());

        when(stuffRepository.findAll()).thenReturn(mockStuff);

        // run
        myService.run();
    }
}

@Service
@RequiredArgsConstructor
public class MyService {

    private final BasicStuffRepository<Stuff> stuffRepository;

    public void run() {
        stuffRepository.findAll().stream() ....
    }
}

Solution

  • Looks like you should use @MockBean not @Mock in test class.

    MockBean is used to add mocks to a Spring ApplicationContext, not only "mock" an real object.