Skip to content

Commit b53ccd9

Browse files
committed
test: demo auto refresh
1 parent 5c8ae3a commit b53ccd9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

LazyCache.UnitTests/CachingServiceMemoryCacheProviderTests.cs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -851,6 +851,45 @@ public async Task GetOrAddAsyncWithImmediateExpirationAndCallbackInTheDelegateDo
851851
Assert.That(callbackHasFired, Is.True);
852852
}
853853

854+
[Test]
855+
public async Task AutoRefresh()
856+
{
857+
var key = "someKey";
858+
var refreshInterval = TimeSpan.FromSeconds(1);
859+
var timesGenerated = 0;
860+
861+
// this is the Func what we are caching
862+
ComplexTestObject GetStuff()
863+
{
864+
timesGenerated++;
865+
return new ComplexTestObject();
866+
}
867+
868+
// this sets up options that will recreate the entry on eviction
869+
MemoryCacheEntryOptions GetOptions()
870+
{
871+
var options = new LazyCacheEntryOptions()
872+
.SetAbsoluteExpiration(refreshInterval, ExpirationMode.ImmediateExpiration);
873+
options.RegisterPostEvictionCallback((keyEvicted, value, reason, state) =>
874+
{
875+
if (reason == EvictionReason.Expired || reason == EvictionReason.TokenExpired)
876+
sut.GetOrAdd(key, _ => GetStuff(), GetOptions());
877+
});
878+
return options;
879+
}
880+
881+
for (var i = 0; i < 3; i++)
882+
{
883+
var thing = sut.GetOrAdd(key, () => GetStuff(), GetOptions());
884+
Assert.That(thing, Is.Not.Null);
885+
await Task.Delay(2 * refreshInterval);
886+
}
887+
888+
// refreshed every second in 6 seconds so generated 6 times
889+
// even though we only fetched it every other second which would be 3 times
890+
Assert.That(timesGenerated, Is.EqualTo(6));
891+
}
892+
854893
[Test]
855894
public async Task GetOrAddAsyncWithImmediateExpirationDoesExpireItems()
856895
{

0 commit comments

Comments
 (0)