如何使用Microsoft Fakes来填充异步任务方法



我正在使用Microsoft Fakes来Shim一个异步方法,该方法调用另一个方法来获得已实现的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。事实上,您永远不应该使用Task构造函数。正如我在博客上描述的那样,它根本没有有效的用例。

相反,使用Task.FromResult:

ConfigurationEntities.Fakes.ShimConfigurationDataContext.AllInstances.GetAccountDataInstanceInt32NullableOfInt32 =
    (x, y, z) => Task.FromResult(new SampleContext());

Task还具有对单元测试有用的其他几种From*方法(例如Task.FromException)。

最新更新