Mock memory cache can be set up like screenshot below.
var firstTime = true;
object? expectedValue = "value from mock";
mockMemoryCache.Setup(x => x.TryGetValue(It.IsAny<object>(), out expectedValue))
.Returns(() =>
{
if (firstTime)
{
firstTime = false;
return false;
}
return true;
});
mockMemoryCache
.Setup(x => x.CreateEntry(It.IsAny<object>()))
.Returns(Mock.Of<ICacheEntry>);
Reference: https://stackoverflow.com/a/11308543/8778795 https://github.com/devlooped/moq/issues/436