如何使用异步方法纠正写测试? [英] How to correct write test with async methods?

查看:17
本文介绍了如何使用异步方法纠正写测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有迭代图像的课程.

public class PictureManager
    {
        private int _current;
        public List<BitmapImage> _images = new List<BitmapImage>(5);
        public static string ImagePath = "dataImages";

        public async void LoadImages()
        {
            _images = await GetImagesAsync();
        }
        public async Task<List<BitmapImage>> GetImagesAsync()
        {
            var files = new List<BitmapImage>();
            StorageFolder picturesFolder = await KnownFolders.PicturesLibrary.GetFolderAsync("dataImages");
            IReadOnlyList<IStorageItem> itemsList = await picturesFolder.GetItemsAsync();
            foreach(var item in itemsList)
            {
                if(!(item is StorageFile)) continue;
                var tempImage = new BitmapImage(new Uri(item.Path));
                Debug.WriteLine(string.Format("add {0}", item.Path));
                files.Add(tempImage);
            }
            return files;

        }
}

我写了这个测试方法(我使用 nUnit):

And I write this test method(I use nUnit):

  [TestFixture]
    public class PictureManagerTest
    {
        private PictureManager _pic;

        [SetUp]
        public void Init()
        {
            _pic = new PictureManager();
            _pic.LoadImages();

        }

        [Test]
        public void ElementOfImagesIsNotNull()
        {
            _pic.GetImagesAsync().ContinueWith(r =>
            {
                BitmapImage image = r.Result[0];
                image = null;
                Assert.IsNotNull(image);
            });
        }
}

为什么这次测试会成功?

Why this test is successful?

推荐答案

nUnit,截至目前,不直接支持异步测试(但是 MSTest 和 xUnit 支持).

nUnit, as of right now, doesn't directly support asynchronous tests (MSTest and xUnit do, however).

您可以通过等待结果来解决此问题,如下所示:

You can work around this by waiting on the results, like so:

    [Test]
    public void ElementOfImagesIsNotNull()
    {
        var continuation = _pic.GetImagesAsync().ContinueWith(r =>
        {
            BitmapImage image = r.Result[0];
            image = null;
            Assert.IsNotNull(image);
        });

        // Block until everything finishes, so the test runner sees this correctly!
        continuation.Wait();
    }

当然,第二种选择是使用像 MSTest 这样的东西,它确实支持测试异步代码,即:

The second option, of course, would be to use something like MSTest, which does support testing asynchronous code, ie:

    [TestMethod]
    public async Task ElementOfImagesIsNotNull()
    {
        var images = await _pic.GetImagesAsync();

        BitmapImage image = r.Result[0];
        image = null;
        Assert.IsNotNull(image);
    }

这篇关于如何使用异步方法纠正写测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆