我有一个具有迭代行为的界面,但在 Rhinomocks 中模拟它时遇到了麻烦。示例接口和类是我的问题的一个非常简单的版本。
每次调用 LineReader.Read() 时,LineReader.CurrentLine() 都应返回不同的值——下一行。到目前为止,我还无法在模拟中重现这种行为。因此,它已经成为我的一个小爱好项目,我会时不时地回顾一下。我希望你能帮助我更进一步。
internal class LineReader : ILineReader
{
private readonly IList<string> _lines;
private int _countOfLines;
private int _place;
public LineReader(IList<string> lines)
{
_lines = lines;
_countOfLines = lines.Count;
_place = 0;
}
public string CurrentLine()
{
if (_place<_countOfLines)
{
return _lines[_place];
}
else
{
return null;
}
}
public bool ReadLine()
{
_place++;
return (_place < _countOfLines);
}
}
编辑添加了不完整的单元测试:
[Test]
public void Test()
{
IList<string> lineListForMock = new List<string>()
{
"A",
"B",
"C"
};
MockRepository mockRepository = new MockRepository();
ILineReader lineReader = mockRepository.Stub<ILineReader>();
//Setup the values here
mockRepository.ReplayAll();
bool read1 = lineReader.ReadLine();
Assert.That(read1, Is.True);
Assert.That(lineReader.CurrentLine(), Is.EqualTo("A"));
bool read2 = lineReader.ReadLine();
Assert.That(read2, Is.True);
Assert.That(lineReader.CurrentLine(), Is.EqualTo("B"));
bool read3 = lineReader.ReadLine();
Assert.That(read3, Is.True);
Assert.That(lineReader.CurrentLine(), Is.EqualTo("C"));
bool read1 = lineReader.ReadLine();
Assert.That(read1, Is.False);
}
这就是您所需要的:
var enumerator = new List<string> { "A", "B", "C" }.GetEnumerator();
var lineReader = MockRepository.GenerateStub<ILineReader>();
lineReader.Stub(x => x.CurrentLine())
.Return("ignored")
.WhenCalled(x => x.ReturnValue = enumerator.Current);
lineReader.Stub(x => x.ReadLine())
.Return(false) // will be ignored
.WhenCalled(x => x.ReturnValue = enumerator.MoveNext());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)