title: Mockito how to test findById() returning an Optional
body: <p>I'm stuck trying to test the findById() method from the CrudRepository.
  This method returns an <code>Optional</code> and I can't figure out how to return it,
  right now its giving me a <code>NullPointerException</code>.</p>
  
  <p>My test code looks as following:</p>
  
  <pre><code>@RunWith(MockitoJUnitRunner.class)
  public class DishServiceMockTest {
  
      private static final String DISH_NAME = "Kaas";
      private static final String DISH_TYPE = "Voorgerecht";
      private static final Long DISH_ID = 23L;
  
      //Mock the service dependencies(=DishServiceImpl is dependent on dishRepo)
      @Mock
      DishRepository dishRepository;
  
      //Mock the service which is to be tested (Can't be a interface)
      @InjectMocks
      DishServiceImpl dishService;
  
  @Test
  public void findById(){
      //Arange
      Dish dish = createDish(DISH_ID, DISH_NAME, DISH_TYPE);
  
      Mockito.when(dishRepository.findById(DISH_ID)).thenReturn(Optional.of(dish));
      assertThat(dishService.findById(DISH_ID)).isEqualTo(dish);
  
  }
  </code></pre>
  
  <p>Running the test gives me 2 errors, one of which is a NullPointerException and the second one: </p>
  
  <pre><code>org.mockito.exceptions.misusing.UnfinishedStubbingException: 
  Unfinished stubbing detected here:
  -&gt; at avans.ivh11.proftaak.mocks.DishServiceMockTest.findById(DishServiceMockTest.java:85)
  
  E.g. thenReturn() may be missing.
  Examples of correct stubbing:
      when(mock.isOk()).thenReturn(true);
      when(mock.isOk()).thenThrow(exception);
      doThrow(exception).when(mock).someVoidMethod();
  Hints:
   1. missing thenReturn()
   2. you are trying to stub a final method, which is not supported
   3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
  </code></pre>
  
  <p>NPE</p>
  
  <pre><code>java.lang.NullPointerException
  at java.util.Objects.requireNonNull(Objects.java:203)
  at java.util.Optional.&lt;init&gt;(Optional.java:96)
  at java.util.Optional.of(Optional.java:108)
  at avans.ivh11.proftaak.mocks.DishServiceMockTest.findById(DishServiceMockTest.java:85)
  </code></pre>
  
  <p>ComparisonFailure</p>
  
  <pre><code>org.junit.ComparisonFailure: 
  Expected :avans.ivh11.proftaak.Domain.Dish@17
  Actual   :Optional[avans.ivh11.proftaak.Domain.Dish@17]
  </code></pre>