0

I have this piece of simple code but couldn't understand its logic and meaning.

void findByIdThrows(){
    given(addressRepository.findById(1)).willThrow(new RuntimeException("boom iii"));

    assertThrows(RuntimeException.class, () -> servic.findById(1));

    then(addressRepository).should().findById(1);
}

Does it mean: if you got a RuntimeException during the finding of the address with id #1 then assert that I'll give the RuntimeException?

What does the last line (then....) do exactly?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
rahman j89
  • 59
  • 8

1 Answers1

0

1-st line:

define call addressRepository.findById(1) will throw RuntimeException

2-st line:

checks if servic.findById(1) throws RuntimeException

3-th line:

equivalent of:

 verify(addressRepository).findById(1)

And checks if the addressRepository.findById(1) was called

  • I called addressRepository.findById(1) at first line. Why should I verify calling of this method again? – rahman j89 Jan 10 '21 at 18:02
  • Because the first line just sets up the mock, so that _if_ the call occurs, then the exception will be thrown. The third line checks whether the call really did occur. – Dawood ibn Kareem Jan 10 '21 at 18:08
  • You wasn't call `addressRepository.findById(1)` in first line - there you say to Mokito thats when somewhere in the test process will be called `addressRepository.findById(1)` then it throws exception – Даниил Дмитроченков Jan 10 '21 at 18:10
  • Thanks dawood-ibn-kareem and Даниил Дмитроченков. Now these lines are meaningful for me. – rahman j89 Jan 10 '21 at 18:16
  • When I change the id number from 1 to 2 at first line, I expect that test be failed but test passed with no errors. Why this happened? I Mocked it with id #1. – rahman j89 Jan 10 '21 at 19:29
  • void findByIdThrows(){ given(addressRepository.findById(2)).willThrow(new RuntimeException("boom iii")); assertThrows(RuntimeException.class, () -> servic.findById(1)); then(addressRepository).should().findById(anyInt()); } In this test I changed the given id to 2 but test didn't give any error. – rahman j89 Jan 11 '21 at 05:31
  • probably this can help https://stackoverflow.com/questions/16243580/mockito-how-to-mock-and-assert-a-thrown-exception – Даниил Дмитроченков Jan 11 '21 at 12:03