c# - 如何使 FileDelete 在单元测试中引发异常
问题描述
这是我编写的一个简单的 Logger 类:
public class Logger : ILogger
{
private readonly string logFilePath;
private readonly object threadLock;
public Logger(string filePath, string fileName)
{
this.logFilePath = Path.Combine(filePath, fileName);
this.threadLock = new object();
}
#region ILogger
void ILogger.Log(string message) => this.DoLog(message);
void ILogger.DeleteLog() => this.DoDelete();
#endregion
[Conditional("DEBUG")]
private void DoLog(string message)
{
//lock (this.threadLock)
//{
string dateTime = DateTime.UtcNow.ToString("O", System.Globalization.CultureInfo.InvariantCulture); // See https://stackoverflow.com/questions/1728404/date-format-yyyy-mm-ddthhmmssz
string logMessage = string.Format("{0} {1}{2}", dateTime, message, Environment.NewLine);
File.AppendAllText(this.logFilePath, logMessage);
//}
}
[Conditional("DEBUG")]
private void DoDelete()
{
//lock (this.threadLock)
//{
File.Delete(this.logFilePath);
//}
}
}
我想让 File.Delete 在我添加一个锁之前失败。
我试过这个单元测试:
[Test]
public void TestMultithreadingDeleteLog()
{
Thread thread1 = new Thread(this.DoLog);
Thread thread2 = new Thread(this.DoDeleteLog);
this.logger.Log("TestMultithreadingDeleteLog");
//
thread1.Start();
thread2.Start();
//
thread1.Join(); // Blocks the current thread until thread1 completes or aborts)
thread2.Join();
}
private void DoLog()
{
for (int x = 0; x < 100; x++)
{
this.logger.Log("ABC");
}
}
private void DoDeleteLog()
{
for (int x = 0; x < 100; x++)
{
this.logger.DeleteLog();
}
}
但它总是通过,即使数量更大。
如何让 File.Delete 引发异常,以便我可以添加锁并检查是否修复了它?
解决方案
推荐阅读
- spss-modeler - 使用 python 执行的 SPSS 流
- regex - .htaccess 重定向 - *.html 到 wordpress url 的正则表达式
- oracle - 错误,在选择过程中?如何解决这个问题?
- c++ - 遍历抽象类的向量
- c++ - 嵌套模板类的模板类模板参数的特化
- android - 如何使用字符串资源而不是硬编码字符串来设置 ViewPager 选项卡标题
- css - CSS媒体查询问题
- java - Java:Solidity solcJ-all 和 etheriumJ - 无法添加依赖项
- php - 多维数组 - 仅打印特定键值
- javascript - 如何在 PixelAdmin 模板中将 select2 依赖插件更新到版本 4.0.6