首页 > 解决方案 > Directory.CreateDirectory() 返回“对路径 '..\\[folder]\\' 的访问被拒绝。” 与 SpecFlow 测试一起使用时出现异常

问题描述

我正在使用 SpecFlow 和 NUnit 创建一些单元测试。

我的一项测试的要求是创建多个测试文件夹。但是,测试运行返回“拒绝访问路径 '..\TestFolder1\'。” 例外。我已经检查并仔细检查了我在父文件夹中是否具有写入权限,已尝试共享父文件夹并确保父文件夹或其任何内容未标记为只读,但错误仍然存​​在。

public static string[] CreateTestFolders()
    {
        _testFolders = new string[] { @"..\TestFolder1\", @"..\TestFolder2\", @"..\TestFolder3\", @"..\TestFolder4\", @"..\TestFolder5\" };

        for (int i = 0; i < _testFolders.Length - 1; i++)
        {
            try
            {
                Directory.CreateDirectory(_testFolders[i]);
            }
            catch(Exception ex)
            {
                string exm = Environment.UserName + " " + ex.Message;
            }
        }
        return _testFolders;
    }

此应用程序已经使用 MSTest 应用了单元测试;此方法在 [ClassInitialize] 测试设置中被调用并且执行没有问题,但是尝试从 SpecFlow 步骤方法调用该方法仍然返回相同的异常。

我正在努力理解这里的问题。有没有我错过的 SpecFlow 测试或 NUnit 的特定内容?

标签: c#unit-testingnunitspecflow

解决方案


因此,事实证明,问题出在 NUnit 上。使用 MSTest 执行的测试将测试项目的 bin 文件夹返回为 Environment.CurrentDirectory, "C:\Code[test_project_folder]\bin\Debug"; 使用 NUnit 执行的测试返回“C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 14.0\COMMON7\IDE\COMMONEXTENSIONS\MICROSOFT\TESTWINDOW”。由于 CurrentDirectory 是“Program Files (x86)”文件夹的子目录,因此出现访问被拒绝问题。

为了解决这个问题,我在我的辅助方法中添加了一个 testDirectory 字符串参数......

public static string[] CreateTestFolders(string testDirectory)
{
    _testFolders = new string[] { @"TestFolder1", @"TestFolder2", @"TestFolder3", @"TestFolder4", @"TestFolder5" };

    for (int i = 0; i < _testFolders.Length - 1; i++)
    {
        try
        {
            _testFolders[i] = Directory.CreateDirectory(testDirectory + _testFolders[i]).FullName;
        }
        catch(Exception ex)
        {
            string exm = Environment.UserName + " " + ex.Message;
        }
    }
    return _testFolders;
}

...并更新了我的方法调用以将 AppDomain.CurrentDomain.BaseDirectory 作为参数传递...

_testFileFolders = StepHelper.CreateTestFolders(AppDomain.CurrentDomain.BaseDirectory);

这个修复产生了我追求的结果。


推荐阅读