0

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

  • Mocking should work, did you use `@Mockbean` instead of `@Mock` because this look like a springboot test. Could be a unit test though looking at the code – stilllearning Jan 02 '23 at 20:26
  • Post the code of your attempt and the result you got – dems98 Jan 02 '23 at 20:30
  • 1
    How do you inject `CryptoService` (or rather the mock) into your service? This part of the code is missing from your question. I'm guessing it is one of the reasons outlined in [Why is my class not calling my mocked methods in unit test?](https://stackoverflow.com/q/74027324/112968) – knittl Jan 02 '23 at 20:47

0 Answers0