[英]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. 我似乎遇到的问题是嘲笑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. 我遇到的问题是当我调用sw.Write(message)时,测试中sw为null。 When I use the commented out line of code that returns a StreamWriter, I get an error saying access to the file is denied. 当我使用注释掉的代码行返回StreamWriter时,我收到一条错误消息,指出对文件的访问被拒绝。 However I do not want to actually read the file on the hard drive. 但是,我不想实际读取硬盘驱动器上的文件。 How can I go about mocking StreamWriter? 我该如何模拟StreamWriter?
On a side note, if I comment out sw.Write(message), my test passes. 附带一提,如果我注释掉sw.Write(message),则测试通过。 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). 当我添加另一个测试以测试sw.Write时出现了这个问题,所以当我添加该代码时,我的旧测试坏了(我发布的那个)。
我最终将代码重构为使用File.WriteAllText和File.AppendText,因此不需要添加其他依赖项。
You need to create mock for StreamWriter and return it in your currently commented out line instead the actual StreamWriter. 您需要为StreamWriter创建模拟,并在当前注释掉的行中返回它,而不是实际的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. 您只需检查在StreamWriter模拟中实际调用了具有给定消息的Write(string)
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.