gpt4 book ai didi

c# - 模拟 while 循环

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:56 24 4
gpt4 key购买 nike

我需要模拟一个 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;
}

如何设置我的方法只返回 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);

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

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

Setting up a member to return different values / throw exceptions on sequential calls:

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

关于c# - 模拟 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50427340/

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