繁体   English   中英

如何测试异步void方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM