如何 return 来自同步代码的任务以进行模拟实现

How to return a task from synchronous code for a mock implementation

我对异步等待经验不多。

我正在尝试为 returns 来自数据库的数据的服务创建模拟。

具体服务class会比较慢,所以接口returns任务如下图:

public interface IReferenceDataService
    {
        Task<List<ReferenceDataResults>> GetReferenceData(string domain, string concept);
    }

我的模拟 class 看起来如下:

public class MockReferenceDataService : IReferenceDataService
{
    public async Task<List<ReferenceDataResults>> GetReferenceData(string domain, string concept)
    {
        List<ReferenceDataResults> ret = new List<ReferenceDataResults>();

        var refDataRepo = new List<ReferenceDataResults>()
        {
            new ReferenceDataResults{ Domain = "Interfaces.Avaloq", Concept = "Client", Key1 = "CE", Value1 = "2", Key2 = "Avaloq", Value2 = "Individual" },
             new ReferenceDataResults{ Domain = "Interfaces.Avaloq", Concept = "Client", Key1 = "CE", Value1 = "3", Key2 = "Avaloq", Value2 = "Joint" } 

        };

        var found = refDataRepo.FindAll(x => x.Domain == domain && x.Concept == concept);

        foreach (var row in found)
        {
            ret.Add(new ReferenceDataResults() { Concept = row.Concept,
                Domain = row.Domain, Key1 = row.Key1, Key2 = row.Key2, Value1 = row.Value1, Value2 = row.Value2 });
        }

        return ret;
    }
}

这给出了编译器警告,因为它被标记为 "async" 但缺少 "await"。 我想最接近数据库检索的是列表中的 FindAll 方法,但似乎没有我可以使用的异步版本的 FindaAll "await".

解决此问题的最佳方法是什么?

由于 async 不构成界面的一部分,请尝试将其删除:

public class MockReferenceDataService : IReferenceDataService
{
    public Task<List<ReferenceDataResults>> GetReferenceData(string domain, string concept)
    {
        // Your code
        return Task.FromResult(ret);
    }
}