2016-04-14 42 views
2

我正在使用Microsoft Fakes来Shim异步方法调用另一个方法来获取实现的DbContext。由于在单元测试中未提供数据库连接字符串,而在async方法内调用的方法需要它。 Shim不仅会跳过使用连接字符串的方法,而且会返回一个可定制的DbContext。如何使用Microsoft Fakes Shim异步任务方法?

下面是aysnc方法实现:

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

    return AccountDataDataContext.GetInstance(account.AccountDataConnectionString); 
} 

不过,我不熟悉沉异步方法。我当时是什么样的:

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的表达完全错误。

有什么建议吗?谢谢。

回答

1

您不想返回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)。

+0

很高兴知道Task构造函数,我只是检查一些关于这个的规格,你是对的。当我到达工作站时,我会在明天尝试Task.FromResult()。谢谢。 –