【问题标题】:Mock a callback function using Mockito使用 Mockito 模拟回调函数
【发布时间】:2021-09-23 16:48:32
【问题描述】:

我正在使用 Junit 在 java 中编写单元测试用例。我有一个带有回调函数的函数。

public class RedisCacheServiceImpl implements CacheService {
  public <T> T useCacheElseCompute(String key, Class<T> valueClass, Supplier<T> compute, Long expiryInSeconds) {
    //  .....Body............
  }
}

在另一个班级

public class NotificationTemplateServiceImpl implements NotificationTemplateService {
public NotificationTemplateDTO getNotificationMessage(NotificationDTO notificationDTO) {
  // .....data....
  NotificationTemplateDTO notificationTemplateDTO = cacheService.useCacheElseCompute(
    templateCacheKey, NotificationTemplateDTO.class,
    () -> notificationTemplateRepository.getNotificationTemplate(notificationType, deliveryType),
    cacheExpiryInSeconds
  );
}
  //.......logic...

我正在为 getNotificationMessage 函数编写单元测试用例,但遇到了Incompatible equality constraint 问题。 单元测试:-

@Test
void testGetNotificationMessage() {
  Mockito.when(mockCacheService.useCacheElseCompute(
    templateCacheKey,
    NotificationTemplateDTO.class,
    ArgumentMatchers.<Supplier<NotificationTemplateRepository>>any()),
    any(Long.class)
  ).thenReturn(null);
}

【问题讨论】:

  • 看起来第二个参数将类型变量 T 设置为 NotificationTemplateDTO 但第三个参数期望 T 为 NotificationTemplateRepository
  • NotificationTemplateRepository 是一个接口。

标签: java spring junit mockito


【解决方案1】:
when(mockCacheService.useCacheElseCompute(eq(templateCacheKey),
                eq(NotificationTemplateDTO.class),any(Supplier.class), eq(86400L))).thenReturn(null);

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多