【发布时间】:2021-11-15 02:13:33
【问题描述】:
注意:我已经查看并尝试了一些关于 SO 的方法,例如How to test Spring's declarative caching support on Spring Data repositories?,但由于它们中的大多数都老了,我无法让它们正常工作,我需要一个具有最新库版本的解决方案。因此,如果您查看问题和帮助,我将不胜感激。
@Service
@EnableCaching
@RequiredArgsConstructor
public class DemoServiceImpl implements DemoService {
private static final String CACHE_NAME = "demoCache";
private final LabelRepository labelRepository;
private final LabelTranslatableRepository translatableRepository;
private final LanguageService languageService;
@Override
public LabelDTO findByUuid(UUID uuid) {
final Label label = labelRepository.findByUuid(uuid)
.orElseThrow(() -> new EntityNotFoundException("Not found."));
final List<LabelTranslatable> translatableList = translatableRepository.findAllByEntityUuid(uuid);
return new LabelDTO(Pair.of(label.getUuid(), label.getKey()), translatableList);
}
}
我创建了以下单元测试来测试上述网络的缓存:
@EnableCaching
@ImportAutoConfiguration(classes = {
CacheAutoConfiguration.class,
RedisAutoConfiguration.class
})
@ExtendWith(MockitoExtension.class)
class TextLabelServiceImpl_deneme_Test {
@Autowired
private CacheManager cacheManager;
@InjectMocks
private LabelService labelService;
@Mock
private LabelRepository labelRepository;
@Mock
private LabelTranslatableRepository translatableRepository;
@Test
void test_Cache() {
UUID uuid = UUID.randomUUID();
final TextLabel textLabel = new TextLabel();
textLabel.setId(1);
textLabel.setKey("key1");
TextLabelTranslatable textLabelTranslatable = new TextLabelTranslatable();
textLabelTranslatable.setEntityUuid(uuid);
textLabelTranslatable.setLanguage(SupportedLanguage.fr);
textLabelTranslatable.setValue("value1");
final List<TextLabelTranslatable> translatableList = new ArrayList<>();
translatableList.add(textLabelTranslatable);
when(labelRepository.findByUuid(uuid)).thenReturn(Optional.of(textLabel));
when(translatableRepository.findAllByEntityUuid(uuid)).thenReturn(translatableList);
TextLabelDTO result1 = labelService.findByUuid(uuid);
TextLabelDTO result2 = labelService.findByUuid(uuid);
assertEquals(result1, result2);
Mockito.verify(translatableRepository, Mockito.times(1)).findAllByEntityUuid(uuid);
}
我不确定我的测试中是否缺少部分,但在最后一行 (Mockito.verify()),它返回 2 而不是 1,这意味着缓存不起作用。但它工作正常,我认为我的测试存在问题。我应该如何完成单元测试以正确检查缓存?
【问题讨论】:
-
还有其他人曾经为 Java 中的缓存创建单元测试吗?
标签: java spring unit-testing testing junit