Issue
I want to mock database call with fake data but I got stuck in the following scenario:
MyService
public class MyService {
// some stuff
Page<SampleDto> sample = repo.findAllSample();
// other stuff
}
I want to stub this with when()
but I am not able to do this. My test is:
MyServiceTest
public class MySampleTest {
@Test
void myTest() {
// initialisation and all stuff
when(myRepo.findAll()).thenReturn(......)
// I want to pass 2 fake SampleDto from
// here but don't know how to do that
}
}
Solution
You can mock the Page
object also if there is a aneed to handle some other functionality inside your service class. Assuming that your service class is actually something like:
public class MyService {
@Resource
private SampleRepository repo;
public Page<SampleDto> findAllSample() {
var sampleData = repo.findAllSample();
// perhaps some operations with sample data and page
return sampleData;
}
}
then the test class could be something like (JUnit4):
@RunWith(MockitoJUnitRunner.class)
public class MySampleTest {
@Mock
private SampleRepository repo;
@Mock
private Page<SampleDto> page;
@InjectMocks
private MyService myService;
@Test
public void test() {
doReturn(page).when(repo).findAll();
var listSampleDtos = List.of(new SampleDto()); // populate with what you need
doReturn(listSampleDtos).when(page).getContent();
var page = myService.findAllSample();
// ... do the asserts, just as an example:
verify(repo).findAll(); // called
assertEquals(1, page.getContent().size());
}
Answered By - pirho