简体   繁体   中英

Mocking StreamWriter (C# Moq)

I am writing a method that will write to a text file. I am still trying to wrap my head around Dependency Inversion.

The issue I appear to be having is with mocking StreamWriter.

Here is my test, I commented out one of the setup lines, as this is where my issue is.

[Test]
    public void WriteToAutomationLog_FileDoesNotExist_CreateFile()
    {
        //arrange
        mockDirectoryWrapper.Setup(_ => _.Exists(It.IsAny<string>())).Returns(true);
        mockFileWrapper.Setup(_ => _.Exists(It.IsAny<string>())).Returns(false);
        mockFileWrapper.Setup(_ => _.CreateText(logFile.GetAutomationLogsPath() + fileName)).Verifiable();
        //mockFileWrapper.Setup(_ => _.CreateText(logFile.GetAutomationLogsPath() + fileName)).Returns(new StreamWriter(fileName)).Verifiable();

        //act
        logFile.WriteToAutomationLog(fileName, message);

        //assert
        mockFileWrapper.Verify(_ => _.CreateText(logFile.GetAutomationLogsPath() + fileName), Times.Exactly(1));
    }

Here is my method I am testing on

public void WriteToAutomationLog(string fileName, string message)
    {
        //Ensure the automation logs path still exists.
        if (_directoryWrapper.Exists(automationLogsPath))
        {
            //Check if file exists
            if (_fileWrapper.Exists(automationLogsPath + fileName))
            {
                //Append to log file
                using (StreamWriter sw = _fileWrapper.AppendText(automationLogsPath + fileName))
                {

                }
            }
            else
            {
                //Create new file
                using (StreamWriter sw = _fileWrapper.CreateText(automationLogsPath + fileName))
                {
                    sw.Write(message);
                }
            }
        }
    }

I have wrappers for the Directory and File class. The issue I am having is when I call sw.Write(message), sw is null in my test. When I use the commented out line of code that returns a StreamWriter, I get an error saying access to the file is denied. However I do not want to actually read the file on the hard drive. How can I go about mocking StreamWriter?

On a side note, if I comment out sw.Write(message), my test passes. This issue came up when I added another test to test sw.Write, so when I added that code my old test broke (the one that I posted).

我最终将代码重构为使用File.WriteAllText和File.AppendText,因此不需要添加其他依赖项。

You need to create mock for StreamWriter and return it in your currently commented out line instead the actual StreamWriter.

Then it won't access the file. You can just check that Write(string) method with given message was actually called on the StreamWriter mock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM