Sven Sven - 3 months ago 40
C# Question

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
in my test which returns the value 1, although I use random values in my real dice:

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.


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.