CodeGo.net>如何使用Microsoft假冒垫片异步任务方法?
作者:互联网
我正在使用Microsoft Fakes来填充异步方法,该方法调用另一个方法来获取已实现的DbContext.因为在async方法内部调用的方法需要它时,单元测试中没有提供数据库连接字符串. 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表达式完全写错了.
有什么建议吗?谢谢.
解决方法:
您不想返回新任务.实际上是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).
标签:asynchronous,shim,c,entity-framework 来源: https://codeday.me/bug/20191027/1942120.html