模拟 while 循环

Gau*_*tam 1 .net c# unit-testing moq

我需要模拟一个 while 循环只运行一次,但是我的设置使它运行无限次,因为我认为它总是返回 true。

我的设置:

var loginName = "12345";

cacheRepository.Setup(m => m.AddString(string.Format("{0}_{1}", Resources.ResetCodeCacheKey, randomCode), loginName)).Returns(true);
Run Code Online (Sandbox Code Playgroud)

while 循环方法:

while (_cacheRepository.AddString(string.Format("{0}_{1}", Resources.ResetCodeCacheKey, code), userLoginName))
{
    //.........
}
Run Code Online (Sandbox Code Playgroud)

添加字符串实现:

public virtual bool AddString(string key, string value)
{
    if (!ExistsKey(key))
    {
        Cache.AddString(key, value);
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

如何设置我的方法只返回 true 一次?代码片段会有所帮助。感谢您对此进行调查。

Nko*_*osi 5

使用SetupSequence设置嘲笑的成员返回所需的结果。

例如说你有以下界面

public interface IInterface {
    bool AddString(string key, string value);
}
Run Code Online (Sandbox Code Playgroud)

设置看起来像

var cacheRepository = new Mock<IInterface>();
cacheRepository
    .SetupSequence(m => m.AddString(It.IsAny<string>(), It.IsAny<string>()))
    .Returns(true)
    .Returns(false);
Run Code Online (Sandbox Code Playgroud)

第一次调用模拟成员时,将返回true,然后false第二次调用。

参考Moq Quickstart以更好地了解如何使用模拟框架。

设置成员以在顺序调用时返回不同的值/抛出异常:

var mock = new Mock<IFoo>();
mock.SetupSequence(f => f.GetCount())
    .Returns(3)  // will be returned on 1st invocation
    .Returns(2)  // will be returned on 2nd invocation
    .Returns(1)  // will be returned on 3rd invocation
    .Returns(0)  // will be returned on 4th invocation
    .Throws(new InvalidOperationException());  // will be thrown on 5th invocation
Run Code Online (Sandbox Code Playgroud)