Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading