如何在特殊文件夹中编写用户权限的MSpec测试

本文关键字:用户 权限 测试 MSpec 文件夹 | 更新日期: 2023-09-27 18:09:59

我有一个便携式应用程序更新程序。在更新应用程序之前,我们检查登录用户是否具有对工作目录的写访问权限。有人知道如何编写断言这些特权的测试吗?

这是相关的代码片段:
try
{
    var security = FolderAndFiles
       .WorkingDirectory
       .GetAccessControl()
       .GetAccessRules(true, true, typeof (NTAccount));
}
catch(UnauthorizedAccessException)
{
    // throw exception
}

如何在特殊文件夹中编写用户权限的MSpec测试

我处理这个问题的一种方法是创建文件系统的抽象,它只包含我需要的功能。在这个例子中,我创建了一个实用程序来从Git日志历史中提取信息。我把所有的方法都变成了虚方法,这样它们就可以被模拟,但是你也可以很容易地定义一个接口。

/// <summary>
///   Class FileSystemService - an abstraction over file system services.
///   This class consists mainly of virtual methods and exists primarily to aid testability.
/// </summary>
public class FileSystemService
    {
    public virtual bool DirectoryExists(string path)
        {
        return Directory.Exists(path);
        }
    public virtual string PathCombine(string path1, string path2)
        {
        return Path.Combine(path1, path2);
        }
    public virtual string GetFullPath(string path)
        {
        return Path.GetFullPath(path);
        }
    public virtual void SaveImage(string path, Bitmap image, ImageFormat format)
        {
        image.Save(path, ImageFormat.Png);
        }
    }

创建了文件系统服务后,将它注入到任何需要它的对象中,如下所示:

class SomeClassThatNeedsTheFileSystem
    {
    public SomeClassThatNeedsTheFileSystem(FileSystemService filesystem = null)
        {
        fileSystem = filesystem ?? new FileSystemService();
        }
    }

注意:这是一个相当小的项目,我不想参与IoC容器,所以我做了"穷人的IoC",使FileSystemService成为一个可选参数,默认值为'null';然后测试null并在构造函数中新建一个FileSystemService。理想情况下,对于更健壮的代码,我会强制设置参数,并强制调用者传递一个FileSystemService。

当需要创建假的时候,我这样做(我使用MSpec和FakeItEasy):

// Some stuff elided for clarity
public class with_fake_filesystem_service
    {
    Establish context = () =>
        {
        Filesystem = A.Fake<FileSystemService>();
        };
    protected static FileSystemService Filesystem;
    }