gpt4 book ai didi

c# - 这个单元测试是否正确实现?

转载 作者:太空狗 更新时间:2023-10-29 22:56:40 31 4
gpt4 key购买 nike

<分区>

我有一个单元测试,旨在检查访问权限,并确保在构造类之前有足够的文件系统访问权限。但是,我认为我的单元测试违反了单元测试原则(FIRST),例如:Isolated/Independent 和 Thorough,它们正在谈论构建独立的单元测试并考虑故障场景的几个方面。我还相信,这种单元测试的实现方式是单元测试 .Net 框架,而不是我编写的代码的功能,因为底层类没有被模拟。但我也想知道您的意见,看看我是对是错。

单元测试说明:

单元测试试图确保 EventFeedFile 的构造函数正在执行检查访问权限的方法。该方法称为 VerifyWritable()。请注意,EventFeedFile 是一个单独的类,而 VerifyWritable() 位于另一个类中。

[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))
{
}
}

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com