Skip to content

A mocking library that creates LazyCache IAppCache system mocks.

License

Notifications You must be signed in to change notification settings

rgvlee/LazyCache.Testing

Repository files navigation

LazyCache.Testing

Codacy Badge Codacy Badge

Overview

LazyCache.Testing is a mocking library that creates LazyCache IAppCache system mocks. It's easy to use (usually just a single line of code) with implementations for both Moq and NSubstitute.

Resources

Usage

Start by creating a mocked caching service using Create.MockedCachingService():

var cacheEntryKey = Fixture.Create<string>();
var expectedResult = Fixture.Create<Guid>();

var mockedCache = Create.MockedCachingService();

var actualResult = mockedCache.GetOrAdd(cacheEntryKey, () => expectedResult, DateTimeOffset.Now.AddMinutes(30));

Assert.That(actualResult, Is.EqualTo(expectedResult));

This creates a mocked IAppCache. If your SUT populates the cache you're done. If it doesn't, or you like your arrange to be verbose, populate it as if you were using the real thing:

var cacheEntryKey = Fixture.Create<string>();
var expectedResult = Fixture.Create<Guid>();

var mockedCache = Create.MockedCachingService();
mockedCache.Add(cacheEntryKey, expectedResult);

var actualResult = mockedCache.Get<Guid>(cacheEntryKey);

Assert.That(actualResult, Is.EqualTo(expectedResult));

The Moq implementation of Create.MockedCachingService() returns the mocked caching service. If you need the mock itself (e.g., to verify an invocation) use Mock.Get(mockedCache):

var cacheEntryKey = Fixture.Create<string>();
var expectedResult = Fixture.Create<Guid>();

var mockedCache = Create.MockedCachingService();

var actualResult = mockedCache.GetOrAdd(cacheEntryKey, () => expectedResult, DateTimeOffset.Now.AddMinutes(30));

var cacheMock = Mock.Get(mockedCache);
cacheMock.Verify(x => x.GetOrAdd(cacheEntryKey, It.IsAny<Func<ICacheEntry, Guid>>(), It.IsAny<MemoryCacheEntryOptions>()), Times.Once);

With regard to verifying invocations, all members of the IAppCache interface except CacheProvider are mocked.

Limitations

  • The CacheProvider is not mocked (in general I think accessing the CacheProvider itself should be avoided; raise an issue if you think it should be supported)

About

A mocking library that creates LazyCache IAppCache system mocks.

Resources

License

Stars

Watchers

Forks