Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 边模仿边循环_C#_.net_Unit Testing_Moq - Fatal编程技术网

C# 边模仿边循环

C# 边模仿边循环,c#,.net,unit-testing,moq,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-loop-in方法: while (_cacheRe

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

我的设置:

var loginName = "12345";

cacheRepository.Setup(m => m.AddString(string.Format("{0}_{1}", Resources.ResetCodeCacheKey, randomCode), loginName)).Returns(true);
While-loop-in方法:

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;
}

如何设置我的方法只返回一次true?代码片段将非常有用。感谢您对此进行研究。

使用
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);

使用
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);

…并且只需添加一个警告,即如果您调试使用SetupSequence的测试,请注意调试器获取值将计为调用。当对属性使用SetupSequence时,这是一个比对方法使用SetupSequence时更大的问题,这里就是这样;但我觉得值得一提。线索是测试在运行时与调试时表现不同。这样的行为是一个…的例子,只是为了增加一个警告,如果您调试使用SetupSequence的测试,请注意调试器获取值被视为调用。当对属性使用SetupSequence时,这是一个比对方法使用SetupSequence时更大的问题,这里就是这样;但我觉得值得一提。线索是测试在运行时与调试时表现不同。这种行为就是一个例子。