让我的头脑全力以赴尝试moq下面的界面。 GetOrSet让我绊倒了。该服务来自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;
}
}
代码示例:
var result = _cacheService.GetOrSet(
cacheKey,
cacheExpiry,
() => this.GetRoutes(routeType));
return result.Select(x => new Route(x));
答案 0 :(得分:1)
基本设置可能如下所示:
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;
}
使用通用方法为实现中所需的任何类型构建模拟。