Sven
Sven

Reputation: 2889

Moq: Setup a property without setter?

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.

Upvotes: 35

Views: 41240

Answers (2)

Jim Johnson
Jim Johnson

Reputation: 1223

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.

Upvotes: 88

Aren
Aren

Reputation: 55976

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.

Upvotes: 22

Related Questions