Create SubDirectory with unauthorized access (for unit test)

280 views Asked by At

I have to create unit tests for a class that will internally enumerates files and folders.

Of course I want to test whether it correctly handles folders with unauthorized access.

In other words: I suspect that one of the methods in the test class will call DirectoryInfo.EnumerateDirectories, and I want to make sure that folders with unauthorized access are skipped.

So I need to create a folder to which my TestObject has no authority to access.

[TestMethod]
[ExpectedException(typeof(SecurityException)]
public void HelpFileCollection_GetFiles_SkipsInaccessibleFolders()
{
    // Test: HelpFileCollection.GetFiles() will skip Folders that are not accessible
    // preparation: create a base Folder and a subfolder with limited security
    DirectoryInfo baseFolder = this.CreateTestFolder();
    DirectoryInfo subFolder = baseFolder.CreateDirectory(...      ??? 

    HelpFilderCollection testObject = new HelpFileCollection
    {
        RootFolder = baseFolder,
        IncludeSubFolders = true,
    }

    // Test: call GetFiles(); expect SecurityException
    testObject.GetFiles();
    Assert.Fail("HelpFileCollection.GetFiles() unexpectedly didn't throw SecurityException");
}

What should I do to make subFolder inaccessible?

1

There are 1 answers

0
Ali Yousefi On BEST ANSWER

Example to make a folder that will show you "access denied" error when you call "EnumerateDirectories,":

            DirectoryInfo baseFolder = new DirectoryInfo("D:\\Test");
            DirectoryInfo subFolder = baseFolder.CreateSubdirectory("HelloWorld");
            var security = new System.Security.AccessControl.DirectorySecurity();
            security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(Environment.UserName, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Deny));
            subFolder.SetAccessControl(security);
            //Get Access denied error
            subFolder.EnumerateDirectories();