title: Junit Test: findById method of the Repository
body: <p>I am new in Junit tests and I have a question about it. Here you can see the method <strong>findById</strong> in my service class:</p>
  <pre><code>@Service
  public class DefaultQuarterService implements QuarterService {
  
      private final QuarterRepository quarterRepository;
  
      public DefaultQuarterService(QuarterRepository quarterRepository) {
          this.quarterRepository = quarterRepository;
      }
  
      @Override
      public QuarterEntity findById(int id) {
  
          return quarterRepository.findById(id)
                  .orElseThrow(() -&gt; new EntityNotFoundException(String.format(&quot;Quarter does not exist for id = %s!&quot;, id)));
      }
  }
  </code></pre>
  <p>And here is my QuarterRepository:</p>
  <pre><code>@Repository
  public interface QuarterRepository extends CrudRepository&lt;QuarterEntity, Integer&gt; {
  }
  </code></pre>
  <p>And here is my Junit implementation for this method:</p>
  <pre><code>@MockBean
  private QuarterRepository quarterRepository;
  
  @Test
  public void throwExceptionWhenQuarterIdNotFound() {
      int id = anyInt();
      when(quarterRepository.findById(id))
              .thenReturn(Optional.empty());
      assertThatAnExceptionWasThrown(String.format(&quot;Quarter does not exist for id = %s!&quot;, id));
  }
  
  public void assertThatAnExceptionWasThrown(
          String errorMsg
  ) {
      expectException.expect(RuntimeException.class);
      expectException.expectMessage(errorMsg);
  }
  </code></pre>
  <p>Unfortunately test doesn't pass. Here the error in terminal:</p>
  <blockquote>
  <p>java.lang.AssertionError: Expected test to throw (an instance of
  java.lang.RuntimeException and exception with message a string
  containing &quot;Quarter does not exist for id = 0!&quot;)</p>
  </blockquote>
  <p>Maybe it is so simple but I can not see what I am missing. I would be so happy if you can direct me. Thanks a lot!</p>