Problem: I need to test method to throw the exception in order to do that I need to return empty ArrayList from the method cryptoService.findAll(). How can I mock it?
The test class CSVServiceTests
class CSVServiceTests {
@Autowired
private CSVService csvService;
@Test
public void generateCSVReportWithEmptyDB() {
Throwable t = Assertions.assertThrows(DataNotFoundException.class,
() -> csvService.generateCSVReport());
assertEquals("...", t.getMessage());
}
}
The class and method which is testing. I need to mock cryptoService.findAll() to return new ArrayList()
@Service
public class CSVServiceImpl implements CSVService {
private final CryptoService cryptoService;
public ByteArrayInputStream generateCSVReport() {
List<Crypto> cryptos = cryptoService.findAll();
// cryptoService.findAll().size() == 6
if (cryptos.size() == 0)
throw new DataNotFoundException("There is not enough data to create a CSV: The DB is empty");
...
}
}
And bellow a method that should be mocked, but this approach doesn't work inside csvService.generateCSVReport()
.
@Mock
private CryptoService cryptoService;
@Test
public void generateCSVReportWithEmptyDB() {
Mockito.when(cryptoService.findAll()).thenReturn(new ArrayList<>());
// cryptoService.findAll().size() == 0
// it will print zero size here, but it doesn't work inside the
// method `csvService.generateCSVReport()`
Throwable t = Assertions.assertThrows(DataNotFoundException.class,
() -> csvService.generateCSVReport());
assertEquals("...", t.getMessage());
}
I tried to mock it, but I couldn't achieve that correctly. I will appreciate your help