gpt4 book ai didi

C# 模拟 Mock

转载 作者:行者123 更新时间:2023-12-02 00:45:38 24 4
gpt4 key购买 nike

我是 C# 模拟的新手,我正在尝试阅读一些代码,但其中一个测试失败了,您能否向我解释一下下面的源代码正在尝试测试什么以及何时会失败?

Mock<StreamWriter> _streamWriterMock;
string[] expectedLines;
.
.
.
foreach (var line in expectedLines)
{
_streamWriterMock.Verify(a => a.Write(line), Times.Exactly(1));
}

最佳答案

验证
您可能想检查被测方法是否被调用,甚至该方法被调用了多少次

只是为了重现这个问题,试试这个代码

class Program
{
static void Main(string[] args)
{
var _streamWriterMock = new Mock<StreamWriter>("output.txt");
string[] expectedLines= new []{"test","test"};

foreach (var expectedLine in expectedLines)
{
_streamWriterMock.Object.Write(expectedLine);
}
foreach (var line in expectedLines)
{
_streamWriterMock.Verify(a=>a.Write(line),Times.Exactly(1));
}

}
}

事实上,如果您尝试使用数组 {"test","test"} 模拟您的代码,您将得到一个异常
预期对 mock 的调用正好是 1 次,但实际是 2 次:a => a.Write("test")

但是如果你的数组是这样的

string[] expectedLines= new []{"test","test1"};

你的模拟将被正确执行

因此您的verify 将检查您的方法是否针对相同的输入被调用了一次。我认为代码的主要目标是省略两次写入相同的输出。

关于C# 模拟 Mock<StreamWriter>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44072469/

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