首页 > 解决方案 > 如何使 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 引发异常,以便我可以添加锁并检查是否修复了它?

标签: c#unit-testingsystem.io.file

解决方案


推荐阅读