How to correct write test with async methods?

末鹿安然 提交于 2020-01-02 14:33:27

问题


I have class for iterating images.

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;

        }
}

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?


回答1:


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

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


来源:https://stackoverflow.com/questions/12625595/how-to-correct-write-test-with-async-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!