【发布时间】:2018-11-01 11:59:50
【问题描述】:
我正在尝试创建 IMemoryCache.TryGetValue 方法的模拟,但它在遇到 cache.Get(cacheKey) 时返回以下错误:
无法转换
'System.Collections.Generic.List`1[ConnectionsModel]' to type 'System.Threading.Tasks.Task`1[System.Collections.Generic.List`1[ConnectionsModel]类型的对象
这是模拟:
private static Mock<IMemoryCache> ConfigureMockCacheWithDataInCache(List<ConnectionsModel> auth0ConnectionsResponse)
{
object value = auth0ConnectionsResponse;
var mockCache = new Mock<IMemoryCache>();
mockCache
.Setup(x => x.TryGetValue(
It.IsAny<object>(), out value
))
.Returns(true);
return mockCache;
}
这里是测试方法:
var connectionList = new List<ConnectionsModel>();
var connectionsModel= new ConnectionsModel()
{
id = "1",
name = "abc",
enabled_cons = new List<string>() { "test" }
};
connectionList.Add(connectionsModel);
var mockObject = ConfigureMockCacheWithDataInCache(connectionList);
var sut = new MyService(mockCache.Object);
// Act
var result = await sut.GetConnection(_clientId);
这是它命中的服务:
public async Task<ConnectionsModel> GetConnection(string clientId)
{
var connections = await _cacheService.GetOrSet("cacheKey", ()=> CallBack());
var connection = connections.FirstOrDefault();
return connection;
}
private async Task<List<ConnectionsModel>> CallBack()
{
string url = url;
_httpClient.BaseAddress = new Uri(BaseUrl);
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<List<ConnectionsModel>>();
}
以及缓存扩展方法:
public static T GetOrSet<T>(this IMemoryCache cache, string cacheKey, Func<T> getItemCallback, double cacheTimeout = 86000) where T : class
{
T item = cache.Get<T>(cacheKey);
if (item == null)
{
item = getItemCallback();
cache.Set(cacheKey, item, DateTime.Now.AddSeconds(cacheTimeout));
}
return item;
}
在T item = cache.Get<T>(cacheKey); 这一行之后,我得到了上述异常。我该如何解决这个问题?
【问题讨论】:
-
您正在传递一个任务并尝试将其分配给任务结果的地方。重新检查扩展方法的逻辑
标签: unit-testing asp.net-core moq xunit