unit-testing - 将 Generic.List 转换为 System.Threading.Task.Generic.List 时出现问题

标签 unit-testing asp.net-core moq xunit

我正在尝试创建 IMemoryCache.TryGetValue 的模拟方法,但当它命中 cache.Get(cacheKey) 时,它会返回以下错误:

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);我收到上述异常。我该如何解决这个问题?

最佳答案

考虑创建扩展的额外重载以允许使用异步 API

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;
}

关于unit-testing - 将 Generic.List 转换为 System.Threading.Task.Generic.List 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53100873/

相关文章:

javascript - 导入 SASS 文件的测试组件时出现语法错误

javascript - JS Fetch API 不适用于具有授权属性的 ASP.NET Core 2 Controller

c# - 从 ASP.NET WEB API 调用 Angular 路由

asp.net - Moq Parent 没有默认构造函数。默认构造函数必须显式定义

c# - 通过安装程序设置模拟属性会导致 'Expression is not a method invocation'

c# - 当构造函数有参数时使用 Moq 实现模拟对象

scala - 在测试中设置 javaOptions for Play/SBT

java - 如何在 Junit 测试中覆盖 catch block ?

asp.net - 模拟的 UserManager 和 roleManager 方法返回 null

asp.net-core - 在没有 BuildServiceProvider() 的情况下为 ConfigureApplicationCookie 设置自定义 SessionStore