我测试使用缓存的服务。 我可以测试一些invocatins,但我不知道如何测试“timeToLiveSeconds”。
ehcache.xml中:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<cache name="countries"
maxEntriesLocalHeap="200"
timeToLiveSeconds="120">
</cache>
</ehcache>
@Component
@CacheConfig(cacheNames = "countries")
public class CountryService {
private final CountryProvider countryProvider;
@Autowired
public CountryService(CountryProvider countryProvider) {
this.countryProvider = countryProvider;
}
@Cacheable
public Country findByCode(String code) {
System.out.println("---> Loading country with code '" + code + "'");
return countryProvider.veryExpensiveOperation(code);
}
}
@Component
public class CountryProvider {
public Country veryExpensiveOperation(String code) {
try {
System.out.println("Very expensive operation for code: " + code);
Thread.sleep(10000);
} catch (Exception e) {}
return new Country(code);
}
}
我的测试:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class CountryServiceTest {
@Autowired
private CountryService countryService;
@Test
public void name() throws Exception {
// given
final String code = "AB";
final Country country = new Country(code);
when(Config.countryProvider.veryExpensiveOperation(code))
.thenReturn(country);
// when
final Country ab = countryService.findByCode(code);
countryService.findByCode(code);
countryService.findByCode(code);
countryService.findByCode(code);
// then
assertThat(ab, equalTo(country));
verify(Config.countryProvider, times(1))
.veryExpensiveOperation(anyString());
}
@TestConfiguration
@EnableCaching
static class Config {
@MockBean
static CountryProvider countryProvider;
@Bean
@Primary
CountryService countryService() {
return new CountryService(countryProvider);
}
}
}
现在我想测试在指定的缓存实时时间后调用次数是否会更多:
@Test
public void name() throws Exception {
// given
final String code = "AB";
final Country country = new Country(code);
when(Config.countryProvider.veryExpensiveOperation(code))
.thenReturn(country);
// when
final Country ab = countryService.findByCode(code);
countryService.findByCode(code);
countryService.findByCode(code);
countryService.findByCode(code);
Thread.sleep(120000);
countryService.findByCode(code);
// then
assertThat(ab, equalTo(country));
verify(Config.countryProvider, times(2))
.veryExpensiveOperation(anyString());
}
但它不起作用,因为我得到1次调用并且通常使用Thread.sleep()不是好习惯。有没有办法模拟延迟时间? 你通常如何测试缓存?