Я застрял, пытаясь протестировать метод findById () из CrudRepository.Этот метод возвращает Optional
, и я не могу понять, как его вернуть, сейчас он дает мне NullPointerException
.
Мой тестовый код выглядит следующим образом:
@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);
}
Запуск теста дает мне 2 ошибки, одна из которых - исключение NullPointerException, а вторая:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> 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
NPE
java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at java.util.Optional.<init>(Optional.java:96)
at java.util.Optional.of(Optional.java:108)
at avans.ivh11.proftaak.mocks.DishServiceMockTest.findById(DishServiceMockTest.java:85)
ComparisonFailure
org.junit.ComparisonFailure:
Expected :avans.ivh11.proftaak.Domain.Dish@17
Actual :Optional[avans.ivh11.proftaak.Domain.Dish@17]