Moq: Setup a property without setter?

Viewed 33928

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 implement Unit-Tests.

2 Answers

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.

Related