c# - 如何使用 Microsoft Fakes 来填充异步任务方法?

标签 c# entity-framework asynchronous shim

我正在使用 Microsoft Fakes 来填充一个异步方法,该方法调用另一个方法来获取已实现的 DbContext。因为在单元测试中没有提供数据库连接字符串,而在异步方法中调用的方法需要它。 Shim 不仅会跳过使用连接字符串的方法,还会返回可自定义的 DbContext。

这是 aysnc 方法的实现:

public async Task<AccountDataDataContext> GetAccountDataInstance(int accountId)
{
    var account = await this.Accounts.FindAsync(accountId);

    return AccountDataDataContext.GetInstance(account.AccountDataConnectionString);
}

但是,我不熟悉 Shim 异步方法。我所做的看起来像这样:
ConfigurationEntities.Fakes.ShimConfigurationDataContext.AllInstances.GetAccountDataInstanceInt32NullableOfInt32 = (x, y, z) => new Task<AccountDataEntities.AccountDataDataContext>(() =>
{
    return new SampleContext();// This is the fake context I created for replacing the AccountDataDataContext.
});

SampleContext 正在实现 AccountDataDataContext 如下:
public class SampleContext: AccountDataDataContext
{
    public SampleContext()
    {
        this.Samples = new TestDbSet<Sample>();

        var data = new AccountDataRepository();

        foreach (var item in data.GetFakeSamples())
        {
            this.Samples.Add(item);
        }
    }
}

下面是测试用例的代码片段:
[TestMethod]
public async Task SampleTest()
{
    using (ShimsContext.Create())
    {
        //Arrange
        SamplesController controller = ArrangeHelper(1);// This invokes the Shim code pasted in the second block and returns SamplesController object in this test class

        var accountId = 1;
        var serviceId = 2;

        //Act
        var response = await controller.GetSamples(accountId, serviceId);// The async method is invoked in the GetSamples(int32, int32) method.

        var result = response.ToList();

        //Assert
        Assert.AreEqual(1, result.Count);
        Assert.AreEqual("body 2", result[0].Body);
    }
}

结果,我的测试用例永远运行。我想我可能会写完全错误的 Shim lamdas 表达式。

有什么建议吗?谢谢你。

最佳答案

您不想返回 new Task .事实上,you should never, ever use the Task constructor .正如我在我的博客中所描述的,它根本没有有效的用例。

相反,使用 Task.FromResult :

ConfigurationEntities.Fakes.ShimConfigurationDataContext.AllInstances.GetAccountDataInstanceInt32NullableOfInt32 =
    (x, y, z) => Task.FromResult(new SampleContext());
Task还有其他几个From*对单元测试有用的方法(例如, Task.FromException )。

关于c# - 如何使用 Microsoft Fakes 来填充异步任务方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36622194/

相关文章:

c# - Asp.Net MVC @helper 模板位于与 App_Code 不同的文件夹中

.net - 在 IQueryable 的 Select 中调用 DTO 转换器

javascript - Cloudsponge 异步 javascript

javascript - 如何使 $http.get 返回响应而不是 promise 对象?

javascript - 是否有任何原子 javascript 操作来处理 Ajax 的异步特性?

c# - Linq 表达式 : Left Join Duplicating Rows

c# - Entity Framework - 通过拆分使大型 edmx 表更易于管理?

c# - Appcenter UWP 分析未经授权

entity-framework - F# 中的 Entity Framework 和匿名类型

sql-server - Entity Framework 不会解决与复合主键的 PK-FK 关系?