简体   繁体   English

如何保存值以便以后返回?

[英]How to save a value to return it later?

I have an interface ILogger that has a LocalTime property to which one could add time with AddToTime . 我有一个接口ILogger具有LocalTime属性,其中一个可能会增加时间AddToTime To mock it appropriately, I tried the following: 为了适当地模拟它,我尝试了以下操作:

int ltime = 0;
var mlog = new Mock<ILogger>();
mlog.Setup(l => l.AddToTime(It.IsAny<int>())).Callback((int s) => {ltime +=s;});
mlog.Setup(l => l.LocalTime).Returns(ltime);

Although it compiles, i does not work: Probably because Returns evaluates the expression ltime at the beginning and so always returns 0 . 尽管可以编译,但我无法使用:可能是因为Returns在开始时对表达式ltime进行求值,因此始终返回0 Any suggestions how one could achieve the indented behaviour? 有什么建议可以实现缩进行为吗?

Edit: I need this to test it with a loop looking like this: 编辑:我需要用它来像下面这样循环测试:

while (log.LocalTime < 1000)
        {
            log.AddToTime(500);
             ....
         }

As I use the time for logging purposes, it cannot simply replaced by a loop with a local variable. 由于我将时间用于记录目的,因此不能简单地将其替换为具有局部变量的循环。 If AddToTime does nothing, the loop cannot be properly tested. 如果AddToTime不执行任何操作,则无法正确测试循环。

This is a test, I suggest you to avoid any logic in your test. 这是一个测试,建议您在测试中避免任何逻辑。 Only place where you should have some logic is SUT you are testing. 您要测试的只有SUT有逻辑的地方。 Otherwise implementation of mocked logger sneaks into test of some other class. 否则,模拟记录器的实现会潜入其他类的测试中。 Simply setup values you are expecting: 只需设置您期望的值即可:

int ltime = 0;
int timeToAdd = 2;
var mlog = new Mock<ILogger>();
mlog.Setup(l => l.AddToTime(timeToAdd));
mlog.Setup(l => l.LocalTime).Returns(ltime + timeToAdd);

I'd even try to avoid last return setup calculation and replaced it with constant expected value. 我什至会尝试避免最后一次返回设置计算,而用恒定的期望值替换它。 But I need to know more about logic you are testing. 但是我需要更多地了解您正在测试的逻辑。

You can use the Returns method instead of the Callback 您可以使用Returns方法代替Callback
Example here: Settings variable values in a Moq Callback() call 这里的示例: 在Moq Callback()调用中设置变量值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM