将Generic.List转换为System.Threading.Task.Generic.List时出现问题 [英] Problem in casting Generic.List to System.Threading.Task.Generic.List
问题描述
我正在尝试创建IMemoryCache.TryGetValue
方法的模拟,但是当它按下cache.Get(cacheKey)
时会返回以下错误:
I am trying to create mock of IMemoryCache.TryGetValue
method but it returns the following error when it hit cache.Get(cacheKey)
:
无法转换类型为'System.Collections.Generic.List'的对象
1[ConnectionsModel]' to type 'System.Threading.Tasks.Task
1 [System.Collections.Generic.List`1 [ConnectionsModel]
Unable to cast object of type '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);
之后,我得到了上面提到的异常.我该如何解决?
After this line T item = cache.Get<T>(cacheKey);
I am getting the above mentioned exception. How can I fix this?
推荐答案
考虑创建扩展的额外重载以允许使用异步API
Consider creating an additional overload of the extension to allow for asynchronous API to be used
public static async Task<T> GetOrSet<T>(this IMemoryCache cache, string cacheKey, Func<Task<T>> getItemCallback, double cacheTimeout = 86000) where T : class
{
T item = cache.Get<T>(cacheKey);
if (item == null)
{
item = await getItemCallback();
cache.Set(cacheKey, item, DateTime.Now.AddSeconds(cacheTimeout));
}
return item;
}
这篇关于将Generic.List转换为System.Threading.Task.Generic.List时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!