2

我正在对一个新的 Win8 Store 应用程序进行单元测试,并注意到我想要避免的竞争条件。所以我正在寻找一种方法来避免这种竞争条件。

我有一个类,在实例化时调用一个方法以确保它具有本地 StorageFolder。我的单元测试只是实例化对象并测试文件夹是否存在。有时文件夹不是,有时它是,所以我认为这是一个竞争条件,因为 CreateFolderAsync 是异步的(显然)。

public class Class1
{
    StorageFolder _localFolder = null;

    public Class1()
    {
        _localFolder = ApplicationData.Current.LocalFolder;
        _setUpStorageFolders();
    }

    public StorageFolder _LocalFolder
    {
        get
        {
            return _localFolder;
        }

    }


    async void _setUpStorageFolders()
    {
        try
        {
            _localFolder = await _localFolder.CreateFolderAsync("TestFolder", CreationCollisionOption.FailIfExists);

        }
        catch (Exception)
        {
            throw;
        }
    }
}

我的单元测试如下所示:

 [TestMethod]
    public void _LocalFolder_Test()
    {
        Class1 ke = new Class1();


        // TODO: Fix Race Condition 
        StorageFolder folder = ke._LocalFolder;

        string folderName = folder.Name;

        Assert.IsTrue(folderName == "TestFolder");

    }
4

1 回答 1

1

正如 Iboshuizen 建议的那样,我会同步执行此操作。这可以通过asynctask和来完成await。有一个陷阱 - 无法在构造函数内部完成设置,Class1因为构造函数不支持 async/await。因为这个SetUpStorageFolders现在是公开的,并且是从测试方法中调用的。

public class Class1
{
    StorageFolder _localFolder = null;

    public Class1()
    {
        _localFolder = ApplicationData.Current.LocalFolder;
                // call to setup removed here because constructors
                // do not support async/ await keywords
    }

    public StorageFolder _LocalFolder
    {
        get
        {
            return _localFolder;
        }

    }

      // now public... (note Task return type)
    async public Task SetUpStorageFolders()
    {
        try
        {
            _localFolder = await _localFolder.CreateFolderAsync("TestFolder", CreationCollisionOption.FailIfExists);

        }
        catch (Exception)
        {
            throw;
        }
    }
}

测试:

 // note the signature change here (async + Task)
 [TestMethod]
    async public Task _LocalFolder_Test()
    {
        Class1 ke = new Class1();
        // synchronous call to SetupStorageFolders - note the await
        await ke.SetUpStorageFolders();

        StorageFolder folder = ke._LocalFolder;

        string folderName = folder.Name;

        Assert.IsTrue(folderName == "TestFolder");
    }
于 2013-01-12T16:08:39.507 回答