如何纠正异步方法写测试?(How to correct write test with async

2019-09-23 02:48发布

我有类迭代图像。

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):

  [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);
            });
        }
}

为什么这个测试是成功?

Answer 1:

NUnit的,截至目前,不直接支持异步测试(但MSTest的和做的xUnit)。

您可以变通的作法是等待的结果,就像这样:

    [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的,它不支持测试异步代码,即:

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

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


文章来源: How to correct write test with async methods?