2015-02-06 47 views
0

我有一個GenericRepository和一個GenericMockRepository。我正在使用async方法。在ASP中正確返回任務<TEntity>

這裏是我的代碼

// GenericRepository - uses a DbContext context subclass with connection strings and stuff 
public Task<TEntity> GetByIDAsync(object id) { 
    return context.FindAsync(id) 
} 

// GenericMockRepository - uses a List<TEntity> entities 
public Task<TEntity> GetByIDAsync(object id) { 

    // THIS DOESN'T WORK 

    return new Task<TEntity>(() => { 
     return entities.SingleOrDefault(entity => { 
      var property = entity.GetType().GetProperty("ID"); 
      if (property != null && property.GetValue(entity) == id) { 
       return true; 
      } 
      return false; 
     }); 
    }); 
} 

基本上,當請求會通過瀏覽器和Controller是由框架實例化的第一個被調用。第二個會從單元測試項目

稱爲對於這兩種情況,控制器的Details()方法是這樣的:

// inside Details() 
Customer customer = await UnitOfWork.CustomerRepository.GetByIDAsync(id.GetValueOrDefault()); 

這裏是測試案例:

[TestMethod] 
    public async void CanRetrieveSingleContact() { 
     //Arrange 
     SetUp(); 
     Customer customer = Customers.FirstOrDefault(); 

     // Act 
     ViewResult result = await Controller.Details(customer.ID) as ViewResult; 

     // Assert 
     Customer model = result.ViewData.Model as Customer; 
     Assert.AreEqual(customer, model); 
    } 

沒有文檔如何異步測試,所以到目前爲止:

  1. 如果我宣佈本次測試方法void,它不會測試
  2. 作爲任務或任務或任務運行,但從來沒有結束,也沒有給出的結果
+0

錯誤是什麼? – 2015-02-06 01:53:25

+0

你可以發佈你的測試代碼嗎? – 2015-02-06 01:56:39

+0

你還創建了'Task'嗎? – 2015-02-06 02:00:40

回答

1

變化

public async void CanRetrieveSingleContact() 

public async Task CanRetrieveSingleContact() 

TAP編程和單元測試有點棘手,是的,它沒有告訴你爲什麼會失敗。

測試資源管理器需要知道它在做什麼。如果您返回void,它會忽略它並繼續其快樂的方式。但如果你返回Task,它知道要等待。你缺少

的另一件事是:

public async Task<TEntity> GetByIDAsync(object id) 

然後

return await Task.FromResult<TEntity>(entities.SingleOrDefault(...)); 

它需要等待您的異步方法。

+0

這樣,它永遠不會結束,就像任務不應該超過5秒,但它永遠不會結束,還有什麼缺失? – 2015-02-06 02:18:38

+0

好吧,讓我再添加一些。 – beautifulcoder 2015-02-06 02:19:18

+0

好的,所以即使對象調用它使用'await'就像這樣:'await mock.GetByIDAsync(5)',它的實現也應該與'await'一起寫在最後一個代碼塊上? – 2015-02-06 02:30:13