开发者

Moq: Setup a property without setter?

开发者 https://www.devze.com 2023-01-22 03:00 出处:网络
I have following class: public class PairOfDice { private Dice d1,d2; public int Value { get { return d1.Value + d2.Value; }

I have following class:

public class PairOfDice
{
    private Dice d1,d2;
    public int Value 
    {
       get { return d1.Value + d2.Value; }
    }
}

Now I would like to use a PairOfDice in my test which returns the value 1, although I use random values in my real dice:

[Test]
public void DoOneStep ()
{
    var mock = new Mock<PairOfDice>();
    mock.Setup(x => x.Value).Return(2);
    PairOfDice d = mock.Object;
    Assert.AreEqual(1, d.Value);
}

Unfortunately I get a Invalid setup on non-overridable member error. What can I do in this situation?

Please note, that this is my first try to imp开发者_如何学Golement Unit-Tests.


You can use .SetupGet on your mock object.

eg.

[Test]
public void DoOneStep ()
{
    var mock = new Mock<PairOfDice>();
    mock.SetupGet(x => x.Value).Returns(1);
    PairOfDice d = mock.Object;
    Assert.AreEqual(1, d.Value);
}

See here for further details.


Your problem is because it's not virtual. Not because you don't have a setter.

Moq cannot build up a Proxy because it cannot override your property. You either need to use an Interface, virtual method, or abstract method.

0

精彩评论

暂无评论...
验证码 换一张
取 消