I have a unit test which is intended to check the access right and also make sure there is enough access right to file system before constructing a class. But, I think my unit test is violating the unit testing principle (FIRST) such as: Isolated/Independent and Thorough which are talking about building an independent unit test and also considering several aspects of failure scenarios. I also believe that this unit test in the way that is implemented is unit testing the .Net framework not the functionality of the code written by me because the underlying class is not mocked. But I would like to know your opinions as well and see how wrong or right I am.
Explanation of the Unit Test:
The unit test is trying to make sure that the constructor of EventFeedFile
is executing a method which is checking the access rights. That method called VerifyWritable()
. Note that the EventFeedFile
is a separate class and the VerifyWritable()
is seating in another class.
[Test]
public void DirectoryNotWritableTest()
{
var tempPath = Path.Combine(Path.GetTempPath(), "EventFileDirectoryWriteDeniedTest");
int pageSize = 10;
try
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
var directoryInfo = Directory.CreateDirectory(tempPath);
var securityRules = directoryInfo.GetAccessControl();
var writeDeniedRule =
new FileSystemAccessRule("Everyone", FileSystemRights.CreateFiles, AccessControlType.Deny);
securityRules.AddAccessRule(writeDeniedRule);
directoryInfo.SetAccessControl(securityRules);
// ReSharper disable once ObjectCreationAsStatement
Assert.Throws<UnauthorizedAccessException>(() => new EventFeedFile(new PersistenceDirectory(tempPath),
pageSize));
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
/// <param name="directory">The directory containing the persistence file.</param>
/// <param name="pageSize">The size of event feed page.</param>
public EventFeedFile(PersistenceDirectory directory, int pageSize)
{
directory.EnsureExists();
directory.VerifyWritable();
mParentDirectory = directory.TargetPath;
mFullName = Path.Combine(mParentDirectory, Constants.FILE_NAME_EVENTPERSISTENCE);
mPageSize = pageSize;
}
public void VerifyWritable()
{
using (File.Create(
Path.Combine(TargetPath, Path.GetRandomFileName()),
1024,
FileOptions.DeleteOnClose))
{
}
}
EventFeedFile
on top of a directory that has been locked down, you should get anUnauthorizedAccessException
, then the test is OK.