简体   繁体   English

如何起订将被间接修改的属性?

[英]How to moq a property that will be indirectly modified?

I am trying to do a very simple thing: Set an initial value to a property, call a method which callback should modify the property value, and read the property at the end. 我正在尝试做一个非常简单的事情:为属性设置初始值,调用回调应修改属性值的方法,并在最后读取属性。

Class Test2 is using ITest1 to automatize some actions. Test2类正在使用ITest1自动执行某些操作。

public interface ITest1
{
    decimal Value { get; set; }
    void Increment();
}

public class Test2
{
    ITest1 test1;
    public Test2(Itest1 test1)
    {
        this.test1 = test1;
    }

    public void Increment()
    {
        this.test1.Increment();
    }
    public Get()
    {
       return this.test1.Value;
    }
}

In order to achieve this behaviour I setted up this test: 为了实现此行为,我设置了此测试:

[TestClass]
public class Test2Test
{
    private Test2 test2;
    private decimal value;

    [TestInitialize]
    public void Setup()
    {
        var test1Mock = new Mock<ITest1>();
        test1Mock.SetupGet(m => m.Value).Returns(value);
        test1Mock
            .Setup(m => m.Increment())
            .Callback(() => value++);

        this.test2= new Test2(test1Mock.Object);
    }

    [TestMethod]
    public void Get_Returns0()
    {
        Assert.AreEqual(0, this.test2.Get());
    }

    [TestMethod]
    public void Get_AfterIncrement_Returns1()
    {
        this.test2.Increment();
        Assert.AreEqual(1, this.test2.Get());
    }
}

The second test is returning always 0. Why is this happening? 第二个测试始终返回0。为什么会这样?

The solution is to return actions instead of variables as: 解决方案是返回操作而不是变量,如下所示:

.Return(() => value) instead of .Return(value) .Return(() => value)而不是.Return(value)

Answer found here . 这里找到答案。

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

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