0

Getting my head all banged up trying to moq the interface below. The GetOrSet has me tripped up. The service comes from here

public interface ICacheService
{
    T GetOrSet<T>(string cackeKey, int expiryInMinutes, Func<T> getItemCallback) where T : class;
}

public class CacheService : ICacheService
{
    public T GetOrSet<T>(string cacheKey, int expiryInMinutes, Func<T> getItemCallback) where T : class
    {

        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(expiryInMinutes));
        }
        return item;
    }
}

Example in code:

var result = _cacheService.GetOrSet(
        cacheKey,
        cacheExpiry,
      () => this.GetRoutes(routeType));
return result.Select(x => new Route(x));
Community
  • 1
  • 1
gnome
  • 1,113
  • 2
  • 11
  • 19

1 Answers1

1

Basic setup could look like:

public static ICacheService GetMockCacheService<T>() where T : class
{
     var mock = new Mock<ICacheService>();

     mock.Setup(service => service.GetOrSet(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<Func<T>>()))
         .Returns(default(T));

     return mock.Object;
}

Use a generic method to build your mock for whatever type you need in the implementation.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112