![](/img/trans.png)
[英]How to test async void DelegateCommand method containing await with xUnit?
[英]How to test an async void method
請考慮以下代碼。 通過調用GetBrands,將為屬性Brands分配適當的數據。
public class BrandsViewModel : ViewModelBase
{
private IEnumerable<Brand> _brands;
public IEnumerable<Brand> Brands
{
get { return _brands; }
set { SetProperty(ref _brands, value); }
}
public async void GetBrands()
{
// ......
Brands = await _dataHelper.GetFavoriteBrands();
// ......
}
}
但如果我按如下所示進行測試,則測試失敗。 如何在方法GetBrands中等待異步調用?
[TestMethod]
public void AllBrandsTest()
{
BrandsViewModel viewModel = new BrandsViewModel();
viewModel.GetBrands();
Assert.IsTrue(viewModel.Brands.Any());
}
這里簡單的答案是:不要讓它成為async void
。 事實上, 永遠不要做的事情async void
,除非絕對必須是作為事件處理工作。 該事async void
失去恰恰是你想在這里為你測試的東西(可能為你真正的代碼)。
使它成為一個async Task
方法,你現在可以等待完成(使用超時)/添加一個延續,並檢查它是退出成功還是異常。
這是一個單詞更改,以:
public async Task GetBrands()
{
// ......
Brands = await _dataHelper.GetFavoriteBrands();
// ......
}
然后在測試中:
[TestMethod]
public async Task AllBrandsTest()
{
BrandsViewModel viewModel = new BrandsViewModel();
var task = viewModel.GetBrands();
Assert.IsTrue(task.Wait(YOUR_TIMEOUT), "failed to load in time");
Assert.IsTrue(viewModel.Brands.Any(), "no brands");
}
您的模型(DTO)正在填充自己(數據訪問)。 這對於一個班級來說太過分了。 通常當你問自己“我怎么能測試這個”時 ,就是重構的時候了。 創建單獨的數據訪問類:
BrandsViewModel viewModel = new BrandsViewModel();
var brandAccess = new BrandsDataAccess();
viewModel.Brands = await brandAccess.GetAllBrands();
Assert.IsTrue(viewModel.Brands.Any());
現在您可以測試BrandsDataAccess.GetAllBrands()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.