我正在对一个新的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");

    }

最佳答案

正如Iboshuizen所建议的,我将同步进行此操作。可以使用asynctaskawait来完成。有一个陷阱-无法在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");
    }

关于c# - 避免竞争条件创建StorageFolder,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14294803/

10-12 14:24