本文以如何mock LocalDateTime的静态方法为例
一. 在gradle.build中引入依赖
dependencies {
testImplementation 'org.mockito:mockito-inline:3.4.6'
}
二. 使用Mockito中的mockStatic方法生成MockedStatic< T > 对象用来mock LocalDateTime.now()方法
try (MockedStatic<LocalDateTime> mockedLocalDateTime = Mockito.mockStatic(LocalDateTime.class)) {
mockedLocalDateTime.when(LocalDateTime::now).thenReturn(defaultLocalDateTime);
when(orderInfoRepository.findById("1")).thenReturn(Optional.of(expectOrderInfoToCancel));
Order actualOrderToCancel = orderInfoService.cancelOrder("1", mockCurrentUser);
assertThat(actualOrderToCancel).usingRecursiveComparison().isEqualTo(expectedOrderDTO);
}