嘲笑循环

时间:2018-05-19 16:29:52

标签: c# .net unit-testing moq

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

我的设置:

var loginName = "12345";

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

while循环方法:

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

添加字符串实现:

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

如何设置我的方法只返回一次真实?代码片段会很有帮助。感谢您查看此内容。

1 个答案:

答案 0 :(得分:3)

使用SetupSequence设置模拟成员以返回所需的结果。

例如,假设您有以下界面

public interface IInterface {
    bool AddString(string key, string value);
}

设置看起来像

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

第一次调用模拟成员时,第一次将返回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