Mockito如何测试findById()返回可选

时间:2019-06-20 19:56:10

标签: java spring-boot spring-mvc junit mockito

我一直在尝试从CrudRepository测试findById()方法。 该方法返回一个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);

}

运行测试会给我两个错误,其中一个是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]

1 个答案:

答案 0 :(得分:1)

此堆栈跟踪

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)

表示{。{1}}来自.thenReturn(Optional.of(dish));是dish。仔细检查您的null方法。

第二个例外是第一个例外的结果

createDish

Mockito.when(dishRepository.findById(DISH_ID)).thenReturn(Optional.of(dish)); 已成功调用,但是调用when thenReturn时必须进行评估-失败了,因此从未进行过Optiona.of调用。

实际上,这不是“运行时”异常,而是后期测试异常。